How do you keep your backing fields organized? (Styles/Patterns) - c#

c# 3.0 offers us getters and setters with compiler generated backing fields - this is really great, but there are plenty of times that you still need to use a backing field.
In a perfect world (opinion), you would be able to do something like
class MyClass {
... stuff ...
public string MyProperty {
private string _myBackingField = "Foo";
get { return _myBackingField; }
set { _myBackingField = value; }
}
}
instead of
class MyClass {
private string _myBackingField = "Foo";
... stuff ...
public string MyProperty {
get { return _myBackingField; }
set { _myBackingField = value; }
}
}
Does anyone have suggestions or techniques which come close to this? Or to put it another way - what is the clearest way to keep your backing fields and properties organized.

I still prefer
class MyClass {
private string _myBackingField = "Foo";
private string _myOtherBackingField = "bar";
... stuff ...
public string MyProperty {
get { return _myBackingField; }
set { _myBackingField = value; }
}
public string MyOtherProperty {
get { return _myOtherBackingField; }
set { _myOtherBackingField = value; }
}
}
If the lack of proximity bothers you, you can put the backing field for each property above the property it services.
class MyClass {
private string _myBackingField = "Foo";
public string MyProperty {
get { return _myBackingField; }
set { _myBackingField = value; }
}
private string _myOtherBackingField = "bar";
public string MyOtherProperty {
get { return _myOtherBackingField; }
set { _myOtherBackingField = value; }
}
}

I tend to keep the backing fields together at the top, but then I do that with method variables too. Perhaps its a carry over from some of the older languages where variable declaration was always the first step, but it just seems more organized to me than declaring variables inline as needed.
If you don't like declaring variables at the top, the closest I've seen to your "ideal" style would be:
private int _integer1 = 0;
public int Integer1
{
get {return _integer1;}
set {_integer1 = value;}
}

What I prefer:
public int Integer1
{
get {return _integer1;}
set {_integer1 = value;}
}
private int _integer1 = 0;
Why?
because the property is much more
important than the backing field so
it should be read as the first.
if you comment your property, what reads nicer?
this
private int _integer1 = 0;
///<summary>
/// this is my property, enjoy it
///</summary>
public int Integer1
{
get {return _integer1;}
set {_integer1 = value;}
}
or
///<summary>
/// this is my property, enjoy it
///</summary>
public int Integer1
{
get {return _integer1;}
set {_integer1 = value;}
}
private int _integer1 = 0;
The approchach with the backing field at the end is much more readable imho. The same holds for applying attributes to the property.

Why would you put "...stuff..." between the property and the field? I'm a firm believer in keeping tightly-coupled things as close as possible:
class MyClass {
... stuff ...
private string _myBackingField = "Foo";
public string MyProperty {
get { return _myBackingField; }
set { _myBackingField = value; }
}
}
I would also not introduce an extra field unless I had to:
because I need logic the in accessors
for (BinaryFormatter) serialization reasons
In the example given, I'd just use an auto prop:
class MyClass {
... stuff ...
public MyClass() {
MyProperty = "Foo";
}
[DefaultValue("Foo")]
public string MyProperty { get;set; }
}
Obviously, some kind of auto-prop syntax that allowed a default would be nice here, but I don't need it, so I don't expect it any time soon. It doesn't solve a big enough problem to be worth much effort...

I agree that the OP's "perfect world" example would be useful. An auto-property wouldn't work for a lazy-loading scenario:
class MyClass
{
... stuff ...
public string MyProperty
{
private string _myBackingField;
get
{
if (_myBackingField == null)
{
myBackingField = ... load field ...;
}
return _myBackingField;
}
set { _myBackingField = value; }
}
}
In fact I raised this as a suggestion on Microsoft Connect some time ago.

In practice, it doesn't seem to matter.
In my experience, once a class passes a certain threshold of complexity (which is basically the threshold between "trivial" and "non-trivial"), I no longer navigate through the class by scrolling around in its source, I navigate by using Go To Definition and Find Usages.
Using linear proximity to imply things about relationships between class members seems like a good idea, but I think it really isn't. If I see this:
private string _Foo;
public string Foo
{
// arbitrarily complex get/set logic
}
the implication is clear: _Foo is used only by the Foo property. That implication's not dependable, though. The only way for me to be certain that there's no code in the class that's manipulating _Foo is to inspect it. Well, if I can't rely on proximity to tell me anything, why should I care about proximity at all?
These days, I just alphabetize my class members from the start. This frees me up from having to think about something (where should I put this member, and why should I choose that place for it?) that doesn't really matter.

Related

Does a simple property need synchronization? [duplicate]

I would like to know if C# automatically implemented properties, like public static T Prop { get; set; }, are thread-safe or not. Thanks!
Section 10.7.4 of the C# specification states:
When a property is specified as an
automatically implemented property, a
hidden backing field is automatically
available for the property, and the
accessors are implemented to read from
and write to that backing field. The
following example:
public class Point {
public int X { get; set; } // automatically implemented
public int Y { get; set; } // automatically implemented
}
is equivalent to the following declaration:
public class Point {
private int x;
private int y;
public int X { get { return x; } set { x = value; } }
public int Y { get { return y; } set { y = value; } }
}
That's what we promise, and that's what you get. The point of auto properties is to do the most basic, simple, cheap thing; if you want to do something fancier then you should write a "real" property.
It appears not. This is the decompilation with Reflector:
private static string Test
{
[CompilerGenerated]
get
{
return <Test>k__BackingField;
}
[CompilerGenerated]
set
{
<Test>k__BackingField = value;
}
}
No. You must wrap them in thread-locking mechanisms.
object _lock = new object();
public static Main(string[] args)
{
lock(_lock)
{
Prop = new T();
}
T val = null;
lock(_lock)
{
val = Prop;
}
}
There is no synchronization provided with automatic properties, including static properties.
If you need full thread safety, you'll want to use your own properties with a backing field, and handle the synchronization yourself.
For completeness, field-like events do have thread-safety built in, but they are alone in this. Automatically implemented properties do not have any such features. You can, however, do something like:
public static double SomeProp
{ // ### NOT RECOMMENDED ###
[MethodImpl(MethodImplOptions.Synchronized)] get;
[MethodImpl(MethodImplOptions.Synchronized)] set;
}
The problem with this is that it will lock the Type, which is a bad thing. I would implement my own synchronization for this, personally.
I don't believe so. I believe they are just syntatic sugar for:
private static T _prop;
public static T Prop
{
get { return _prop; }
set { _prop = value; }
}
No, they not threadsafe. Static properties just as vulnerable as static fields are to concurrency issues.

Property never null c#

When refactoring code, I come up with instances like the following
private string _property = string.Empty;
public string Property
{
set { _property = value ?? string.Empty); }
}
Later on in a method I see the following:
if (_property != null)
{
//...
}
Assuming that _property is only set by the setter of Property, is this code redundant?
I.e is there any way, through reflection wizardry or other methods that _property can ever be null?
Assuming that _property is only set by the setter of Property, is this
code redundant?
Exactly, it is redundant. This is the actual purpose of Properties. We shouldn't access the fields of a class directly. We should access them using a Property. So in the corresponding setter, we can embed any logic and we can rest assure that each time we try to set a value this logic would be verified once more.This argument holds even for the methods of a class. In a method we must use the properties and not the actual fields. Furthermore, when we want to read the value of a field, we should make use of the corresponding getter.
In general, properties enhances the concept of encapsulation, which is one of the pillars of object oriented programming OOP.
Many times there isn't any logic that should be applied when we want to set a value. Take for instance the following example:
public class Customer
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
We have declared a class for representing a Customer. A Customer object should have three properties an Id, a FirstName and a LastName.
An immediate question, when someones read this class is why should someone make use of properties here?
The answer is again the same, they provide a mechanism of encapsulation. But let's consider how can this help us in the long run. Let's say that one day someone decides that the first name of a customer should be a string of length less than 20. If the above class had been declared as below:
public class Customer
{
public int Id;
public string FirstName;
public string LastName;
}
then we should check for the length of FirstName in each instance we had created ! Otherwise, if we had picked the declaration with the properties, we could just easily make use of Data Annotations
public class Customer
{
public int Id { get; set; }
[StringLength(20)]
public string FirstName { get; set; }
public string LastName { get; set; }
}
and that's it. Another approach it could be the following:
public class Customer
{
public int Id { get; set; }
private string firstName;
public string FirstName
{
get { return firstName }
set
{
if(value!=null && value.length<20)
{
firstName = value;
}
else
{
throw new ArgumentException("The first name must have at maxium 20 characters", "value");
}
}
}
public string LastName { get; set; }
}
Consider both of the above approaches with having to revisit all your codebase and make this check. It's crystal clear that properties win.
Yes, it is possible through reflection. Nevertheless, I wouldn't worry about reflection -- people using reflection to defeat the design of your class is not something I worry about.
There is, however, something I do worry about: the phrase "Assuming that _property is only set by the setter of Property" is key. You are preventing users of your class from setting property to null.
You do not prevent, however, yourself or some other maintainer of your class from forgetting to only use the property INSIDE your class. In fact, your example has some one checking the field from inside the class rather than the property itself.... which means that, within your class, access comes from both the field and the property.
In most cases (where the problem could only come from inside the class) I would use an assertion and assert the field is not null.
If I really, really, really wanted to make sure that it wasn't null (barring reflection or people hell-bent on breaking things), you could try something like this:
internal class Program
{
static void Main()
{
string example = "Spencer the Cat";
UsesNeverNull neverNullUser = new UsesNeverNull(example);
Console.WriteLine(neverNullUser.TheString);
neverNullUser.TheString = null;
Debug.Assert(neverNullUser.TheString != null);
Console.WriteLine(neverNullUser.TheString);
neverNullUser.TheString = "Maximus the Bird";
Console.WriteLine(neverNullUser.TheString);
}
}
public class UsesNeverNull
{
public string TheString
{
get { return _stringValue.Value; }
set { _stringValue.Value = value; }
}
public UsesNeverNull(string s)
{
TheString = s;
}
private readonly NeverNull<string> _stringValue = new NeverNull<string>(string.Empty, str => str ?? string.Empty);
}
public class NeverNull<T> where T : class
{
public NeverNull(T initialValue, Func<T, T> nullProtector)
{
if (nullProtector == null)
{
var ex = new ArgumentNullException(nameof(nullProtector));
throw ex;
}
_value = nullProtector(initialValue);
_nullProtector = nullProtector;
}
public T Value
{
get { return _nullProtector(_value); }
set { _value = _nullProtector(value); }
}
private T _value;
private readonly Func<T, T> _nullProtector;
}
It is basically redundant. However, if it were mission critical or if for some reason it caused terrible side effects, it could remain. It is hard to tell, but part of your question was "can reflection change this value to null" to which the answer is yes and can be seen here in this linqpad demo
void Main()
{
var test = new Test();
test.Property = "5";
Console.WriteLine(test.Property);//5
FieldInfo fieldInfo = test.GetType().GetField("_property",BindingFlags.NonPublic | BindingFlags.Instance);
fieldInfo.SetValue(test, null);
Console.WriteLine(test.Property);//null
}
public class Test
{
private string _property = string.Empty;
public string Property
{
get { return _property; }
set { _property = value ?? string.Empty; }
}
}
I know this question is old, but look, I needed that one of my string properties never came up in null.
So I did this, and It worked for me
public string Operation { get; set; } = string.Empty;
In this way the default value is a string empty, but never null.

What's the difference between a property with a private setter and a property with no setter?

If I want a read-only property, I write it like:
public int MyProperty { get { //Code goes here } }
However, the Microsoft example (and a few other examples I've seen) are written like:
public int MyProperty { get; private set; }
Is there any difference between these two, and should I start writing properties like this?
As you can see in your second sample, you can leave out the implementation for a property. .NET will then automatically create a local variable for the property and implement simple getting and setting.
public int MyProperty { get; private set; }
is actually equivalent to
private int _myProperty;
public int MyProperty {
get { return _myProperty; }
private set { _myProperty = value; }
}
Writing
public int MyProperty { get; }
does not work at all, as automatic properties need to implement a getter and a setter, while
public int MyProperty { get; private set; }
leaves you with a property that may return any int, but can only be changed within the current class.
public int MyProperty { get { ... } }
creates a read-only property.
Question is: what do you need? If you already have a member variable that's used within your class and you only want to return the current value using a property, you're perfectly fine with
public int MyProperty { get { return ...; }}
However, if you want a read-only property, which you need to set within your code (but not from other classes) without explicitly declaring a member variable, you have to go with the private set approach.
With private setter you can only assign property value inside of instance when property is without setter you can't set its value anywhere.
If you don't use an explicit member assignment in the property, you'll have to declare a private set at least in order to be able to set a value to this property. Otherwise, you'll get a warning at compile-time saying that your property cannot be assigned.
If you use an explicit member, you'll be able to assign a value to this member directly, without needing to add a private set:
private int member ;
public int MyProperty {
get { return member; }
}
// ...
member = 2;
int anotherVariable = MyProperty; // anotherVariable == 2
public int MyProperty
{
get
{
// Your own logic, like lazy loading
return _myProperty ?? (_myProperty = GetMyProperty());
}
}
A property with only a getter is very useful if you need your own logic behind the access of that property, in particular when you need the property to be lazy loaded.
public int MyProperty { get; private set; }
A property with a private setter is useful if you need the property not te be changed from the outside, but still maintained from within the class.
In both cases, you can have a backing data field for the actual value, but in the former, you'll have to maintain that yourself, and in the latter, it is maintained for you by the generated code.
There is a difference when you access the object with reflection.
public class Foo
{
public string Bar { get; private set; }
}
// .....
internal static void Main()
{
Foo foo = new Foo();
foo.GetType().GetProperty("Bar").SetValue(foo, "private?", null);
Console.WriteLine(foo.Bar);
}

What is the purpose of accessors?

Can somebody help me understand the get & set?
Why are they needed? I can just make a public variable.
Warning: I am assuming you already know about object-oriented programming.
What are properties?
Properties are language elements that allow you to avoid the repetitive getXYZ() accessors and setXYZ() mutators techniques found in other languages, like Java.
Why do they exist?
They aim to solve the following problems:
Saying get and set in the beginning of every access or mutation of a value is annoying and distracting.
In Java, you often say:
class person
{
private int _age;
public void setAge(int value) { /*check value first, then set _age*/ }
public int getAge() { return this._age; }
}
and then consistently say:
if (person.getAge() > blah || person.getAge() < 10)
{
person.setAge(5);
}
After a while, the get and set become rather annoying.
Providing direct access to the actual variable breaks encapsulation, so that's not an option.
How are they used?
They are used just like variables. You read/write to them just like variables.
How are they created?
They are created as methods. You define a pair of methods that:
Return the current value of the property. Oftentimes, this is nothing more than something like the following:
class Person
{
private int _age; //Declare the backing field
public int Age
{
get { return this._age; }
set { ... }
}
}
Set the value of the property:
class Person
{
public int Age
{
get { ... }
set
{
if (value < 0) //'value' is what the user provided
{ throw new ArgumentOutOfRangeException(); } //Check validity
this._age = value;
}
}
}
Other notes:
Auto-implemented Properties
C# 3.0 introduced auto-implemented properties:
public int Age { get; set; }
This is equivalent to:
private int _age; //The name is auto-generated
public int Age { get { return this._age; } set { this._age = value; } }
Why does it exist?
It helps you avoiding breaking changes in client executables.
Let's say you're lazy and don't want to type the whole thing, and decide to expose a variable publicly. You then create an executable that reads from or writes to that field. Then you change your mind and decide that you in fact needed a property, so you change it to one.
What happens?
The depending executable breaks, because the code is no longer valid.
Auto-implemented properties help you avoid that, without extra redundancy in your initial code.
Indexers
Indexers extend the property syntax to let you index objects (surprise!), just like arrays.
For C++ users: This is similar to overloading operator [].
Example:
private int[] _elements;
public int this[int index] //Indexed property
{
get { return this._elements[index]; }
set
{
//Do any checks on the index and value
this._elements[index] = value;
}
}
You then use them like obj[5] = 10;, which is equivalent to calling the set method of obj's indexer.
In fact, System.Collections.Generic.List<T> is indexed:
var list = new List<int>();
list.Add(10);
list[0] = 5; //You're indexing list, as though it were an array!
Isn't that neat? :)
Anything else?
There are many more features to properties, not all of which are available in C#:
Parametrized properties, of which indexers are a special kind
Getter/setter access modifiers (in C#)
Multiple getters or setters (not in C#)
Et cetera
They are called Accessors
The accessor of a property contains the executable statements associated with getting (reading or computing) or setting (writing) the property. The accessor declarations can contain a get accessor, a set accessor, or both.
The body of the get accessor resembles that of a method. It must return a value of the property type.
http://msdn.microsoft.com/en-us/library/w86s7x04.aspx
private string m_Name; // the name field
public string Name // the Name property
{
get
{
return m_Name;
}
}
The set accessor resembles a method whose return type is void. It uses an implicit parameter called value, whose type is the type of the property.
private m_Name;
public string Name {
get {
return m_Name;
}
set {
m_Name = value;
}
}
Then in the incarnation of C# 3, you can do this much easier through auto-properties
public string Name {get; set; } // read and write
public string Name {get; } // read only
public string Name { get; private set; } //read and parent write
http://msdn.microsoft.com/en-us/library/bb384054.aspx
Properties act as accessors to the internal state of an object, hiding the implementation of that state.
So, for example, you may have a first name property in a class
public class Example
{
private string firstName;
public string FirstName
{
get {return this.firstName;}
}
}
So anyone using the class doesn't need to know how first name is stored, they just know they can get a string representation of it. By adding a set you also add a mutator, something which changes an objects internal state
public class Example
{
private string firstName;
public string FirstName
{
get {return this.firstName;}
set {set this.firstName = value;}
}
}
Again you're still isolating how the first name is stored internally (encapsulation), but users can change it by passing in a string.
Simply put, get and set accessors are the functions called on a Property; that is, when you retrieve the value or when you set it. It forces a type of behavior on the way values are retrieved or set.
For example, you may want to have a mechanism to get/set passwords. Generally speaking, you'll only want to compare the hash of a password instead of storing things plaintext, so you'd have the getter variable retrieve the stored hash, and the setter would take the provided input and hash it for storage.
Here's what I mean:
public class User {
//Usery properties here, and...
private string _password;
public string Password {
get {
return _password;
}
set {
_password = SomeHashingFunction(value);
}
}
}
value is the variable provided to the setter from what has been given in the variable assignment. e.g.: someuser.Password = "blah";
Get and set are used in properties. They can each be public, protected, or private. Similar to accessor and mutator methods, they allow some computation when code tries to access/mutate the property. Of course, as long as you define one of get/set, the other is optional.
Example without properties:
private int test;
public int getTest() {
// some computation on test here, maybe?
return test;
}
private void setTest(int test) {
// some error/range checking, maybe?
this.test = test;
}
With properties:
private int test;
public int Test {
get {
// some computation on test here, maybe?
return test;
}
private set {
// some error/range checking, maybe?
test = value; // value is a keyword here
}
}
get{} and set{} are accessors that offer up the ability to easily read and write to private fields. Working with a simple example:
public class Foo()
{
//Field
private int _bar;
//Property
public int Bar
{
get { return _bar; }
set { _bar = value; }
//value is an implicit parameter to the set acccessor.
//When you perform an assignment to the property, the value you
//assign is the value in "value"
}
}
In this case, Bar is a public property that has a getter and a setter that allows access to the private field _bar that would otherwise be inaccessible beyond class Foo.
Now in a class that has an instace of Foo, you can do this:
public class IHasAFoo()
{
private Foo _myFoo = new Foo();
public void SomeMethod()
{
_myFoo.Bar = 42;
}
}
So the public accessor allows you to set the value of the private field back in Foo.
Hope that helps!

Are C# auto-implemented static properties thread-safe?

I would like to know if C# automatically implemented properties, like public static T Prop { get; set; }, are thread-safe or not. Thanks!
Section 10.7.4 of the C# specification states:
When a property is specified as an
automatically implemented property, a
hidden backing field is automatically
available for the property, and the
accessors are implemented to read from
and write to that backing field. The
following example:
public class Point {
public int X { get; set; } // automatically implemented
public int Y { get; set; } // automatically implemented
}
is equivalent to the following declaration:
public class Point {
private int x;
private int y;
public int X { get { return x; } set { x = value; } }
public int Y { get { return y; } set { y = value; } }
}
That's what we promise, and that's what you get. The point of auto properties is to do the most basic, simple, cheap thing; if you want to do something fancier then you should write a "real" property.
It appears not. This is the decompilation with Reflector:
private static string Test
{
[CompilerGenerated]
get
{
return <Test>k__BackingField;
}
[CompilerGenerated]
set
{
<Test>k__BackingField = value;
}
}
No. You must wrap them in thread-locking mechanisms.
object _lock = new object();
public static Main(string[] args)
{
lock(_lock)
{
Prop = new T();
}
T val = null;
lock(_lock)
{
val = Prop;
}
}
There is no synchronization provided with automatic properties, including static properties.
If you need full thread safety, you'll want to use your own properties with a backing field, and handle the synchronization yourself.
For completeness, field-like events do have thread-safety built in, but they are alone in this. Automatically implemented properties do not have any such features. You can, however, do something like:
public static double SomeProp
{ // ### NOT RECOMMENDED ###
[MethodImpl(MethodImplOptions.Synchronized)] get;
[MethodImpl(MethodImplOptions.Synchronized)] set;
}
The problem with this is that it will lock the Type, which is a bad thing. I would implement my own synchronization for this, personally.
I don't believe so. I believe they are just syntatic sugar for:
private static T _prop;
public static T Prop
{
get { return _prop; }
set { _prop = value; }
}
No, they not threadsafe. Static properties just as vulnerable as static fields are to concurrency issues.

Categories

Resources