C# 3.0 auto
Note: This was posted when I was starting out C#. With 2014 knowledge, I can truly say that auto-properties are among the best things that ever happened to the C# language.
I am used to create my properties in C# using a private and a public field:
private string title;
public string Title
{
get { return title; }
set { title = value; }
}
Now, with .NET 3.0, we got auto-properties:
public string Title { get; set; }
I know this is more a philosophical/subjective questions, but is there any reason to use these auto-properties except from saving five lines of code for each field? My personal gripe is that those properties are hiding stuff from me, and I am not a big fan of black magic.
In fact, the hidden private field does not even show up in the debugger, which is OK given the fact that the get/set functions do nothing. But when I want to actually implement some getter/setter logic, I have to use the private/public pair anyway.
I see the benefit that I save a lot of code (one vs six lines) without losing the ability to change the getter/setter logic later, but then again I can already do that by simply declaring a public field "Public string Title" without the need of the { get; set; } block, thus even saving more code.
So, what am I missing here? Why would anyone actually want to use auto-properties?
We use them all the time in Stack Overflow.
You may also be interested in a discussion of Properties vs. Public Variables. IMHO that's really what this is a reaction to, and for that purpose, it's great.
Yes, it does just save code. It's miles easier to read when you have loads of them. They're quicker to write and easier to maintain. Saving code is always a good goal.
You can set different scopes:
public string PropertyName { get; private set; }
So that the property can only be changed inside the class. This isn't really immutable as you can still access the private setter through reflection.
As of C#6 you can also create true readonly
properties - ie immutable properties that cannot be changed outside of the constructor:
public string PropertyName { get; }
public MyClass() { this.PropertyName = "whatever"; }
At compile time that will become:
readonly string pName;
public string PropertyName { get { return this.pName; } }
public MyClass() { this.pName = "whatever"; }
In immutable classes with a lot of members this saves a lot of excess code.
The three big downsides to using fields instead of properties are:
上一篇: 初始化C#自动
下一篇: C#3.0 auto