Click here to Skip to main content
15,881,173 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I've read quite a few great articles on CodeProject where the author declares properties in the following manner:

C#
public class TestClass
{
    public string FirstName { get; set; }   

    public TestClass()
    {...}

    ...
}


Notice that the FirstName property is declared with get; and set;, but without using any other declared variables. In a couple of C# books that I've read, the authors say it is a good coding practice to declare the variables for the properties to use as such:

C#
public class TestClass
{
    private string _firstName;

    public string FirstName
    {
      get { return _firstName; }
      set { _firstName = value; }
    }
}



I understand that in my first example the compiler will create it's own variable and assign it to the property and we don't have to worry the creation at all. In the books I read the authors said this is a bad idea because there can potentially be some conflicts with your code down the road if you accidentally somehow use the assigned variable somewhere else in the class without realizing it.

What are your thoughts on this?

Thanks,
Jeramy

P.S. If this is a question best left for the forums please let me know and I'll post it there.
Posted

"Proper" use is pretty subjective, there is no hard rule on this.

What I do is typically use auto-generated backing fields for my metadata classes. These are classes that do not have any code (or very little serializing code).

The bigger more involved classes I usually implement them specifically, although I do like to use interfaces like INotifyPropertyChanged and some other things that require more involved getters/setters. You are pretty safe using auto-generated backing fields and it would be pretty rare that you run into a naming issue with what the compiler generates.

Its just coding style, but I will say the earlier you adopt a style of programming and stick with it, the better and more maintainable your code will be.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 17-Jun-13 22:42pm    
There is something which you probably missed. Please see my answer and check up things by yourself. The statement about the conflict of names is based on some misconception.
—SA
Ron Beyer 17-Jun-13 23:07pm    
You are right, symantically you cannot have a conflict since the backing fields are named in the format: <propertyName>k__backingField and the < and > are not available for variable naming. +5 on yours.
Sergey Alexandrovich Kryukov 17-Jun-13 23:40pm    
Great. Thank you, Ron.
—SA
Surendra Adhikari SA 18-Jun-13 0:38am    
Ok . This is really a great explanation . It trigger my mind to update my concept and i'm going to remove my solution .Thanks SA. my 5+ also
Historically, the second approach was created first, and only later the semantically equivalent syntax of auto-implemented properties emerged. The benefit of this new syntax in development looks quite apparent, let's not discuss it.

Let's discuss only the potential name conflict you just mentioned. Apparently, the conflicts are possible. But what are the implications of them? The simple fact is: you don't add many potential conflicts compared to the simple fact that one or two hidden names are already created: the names for setter and getter, but these names are standardized. I tested the code showing the backed field names:
C#
class Program {
    int autoImplementedProperty { get; set; }
    static void Main(string[] args) {
        Type tp = typeof(Program);
        FieldInfo[] fi = tp.GetFields(BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public);
        System.Console.WriteLine(fi[0]);
    }
}

Look at the result: the backing name appeared to be: "<autoImplementedProperty>k__BackingField". It is simply syntactically impossible to code any name conflicting with this one!

And now, if you are simply using properties, even not auto-implemented, you actually can have a conflict which is worse. Add this method:
C#
int get_autoImplementedProperty() { return 0; }
or this:
C#
void set_autoImplementedProperty(int value) { }

In either case, you get an error message: "Type 'Program' already defines a member called '<method_name>' with the same parameter types".

So, where is the problem? Actually, Microsoft created original conflicting situation, and the solution was the standardization of the backing method names. You simply should know these names and avoid them. Is it good? Not quite. Is it a real problem? No, because — try to do it and see how easy the fix would be: you simply read the compilation error message and rename the method appropriately.

By some reason, the authors of those "couple of C# books" don't see a problem here, even though the situation is not quite perfect. They see a problem where it is impossible to create a conflict, simply because they don't understand the essence of things: the auto-generated backing field names are simply syntactically impossible. They told you something which is directly opposite the real situation. The problem can only appear in some hypothetical future language where the name of members could be some XML text. But this is a problem of the authors of such languages and compilers. Hope, they are going to be less stupid than the authors of those "couple of C# books".

The real problem is that there is no any guarantee that the backing field keep there names during compilation. Theoretically speaking, it's possible to get those name via Reflection and use it somewhere, importantly, in Persistence. Is it a problem or not? I think this is not a problem: this is a stupidity which is too sophisticated to be taken seriously. Not that this is impossible: of course, programming should be based on assumption that any stupid use can take place. How about this kind of stupidity? I'm sure that it's not a problem, in the following sense: simply put, such a sophisticated design mistake can be done only by a person who has the talent to screw up things much worse. We all understand that programming systems should not protect from sophisticated stupid tricks but should only promote stable well-supportable style of programming.

And finally, I must say a work of those "couple of C# books". Many, many books on practical software development (concrete systems and languages), development method, organization of development are a permanent source of frustration for me, in such rare moments when I go to the bookstore and scan them. I almost never see decent books on the topics I can judge about. You need to be careful and use your own brain.

—SA
 
Share this answer
 
v3
Comments
jeramyRR 18-Jun-13 5:25am    
Thank you for taking the time to answer this, and more so for providing code to backup your answer.
Sergey Alexandrovich Kryukov 18-Jun-13 7:46am    
You are very welcome.
Good luck, call again.
—SA
When it is such a simple situation like the one you described (just get and set without any extras), I prefer the short style.
But sometimes, some extras are required, mainly with the setter: e.g. checking for a valid value (not null, bigger than x, smaller than y, ...), or firing a PropertyChanged event, or Logging, ... And then you need the more verbous style.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900