Basic Property Coding Conventions in C# 3
This is a question that is arguably aesthetic: the following two classes are functionally equivalent. Which way would you prefer to write your classes?
public class Fooor
{
public string Name
{
get;
private set;
}
public Foo(string name)
{
Name = name;
}
}
public class FooDoes one stand out to you as the better way?
{
private string m_Name;
public string Name
{
get { return m_Name; }
}
public Foo(string name)
{
m_Name = name;
}
}
Labels: C#


5 Comments:
# public string Name
# {
# get;
# private set;
# }
# public Foo(string name)
# {
# Name = name;
# }
I have never seen the first syntax. One benefit is that it will be sure you never mix _name and Name. Does it support lazy initialization?
Rob
Never seen the first syntax. One benefit is that it stops you from mixing _name and Name references within the class. Does it support lazy initialization?
Rob
Yeah, I like the first one better.
In NHibernate it does support lazy initialization. The trick is, you must use the default NHibernate property-access column mapping.
If you use some of the PostSharp attributes, you can use custom validators and INotifyPropertyChanged all without declaring a private variable.
I like
public string Name
{
get;
private set;
}
because I like concise code and it can be written as:
public string Name { get; private set;}
I also like concise code but I prefere the second code fragment anyway. There is something dangerous with the second code. If you have more than just one single property it is a matter of fact that lots use Copy-Paste and just rename the fields. It can happen that you forget to rename something and the property doesn't do the thing it should (ex. writes the value in the Set to another field than expected).
The main advantage I see in the second code is that you can stick to the coding guidelines of your company.
Roman
Post a Comment
<< Home