Ok, this is not new news but, after talking with a few of my colleagues, I recently realized there are still people who don't know about it. So here's a brief explanation... Properties in C# usually consist of a private member variable and a property to read/set values from/to that variable. They look something like this:
public class DocumentInfo
{
private string _path;
private Int32 _docId;
public string Path
{
get
{
return _path;
}
set
{
_path = value;
}
}
public Int32 DocumentId
{
get
{
return _docId;
}
set
{
_docId = value;
}
}
}
Now, in cases like this where there is no get/set logic inside the properties you can easily reduce the amount of code by using automatic properties and letting the compiler fill in the blanks. Automatic properties basically allow you to bypass coding the get/set sections as well as the private member variable, like this:
public class DocumentInfo
{
public string Path { get; set; }
public Int32 DocumentId { get; set; }
}
This, as you can see, significantly reduces the amount of code you have to write. Of course, if you need get or set validation or other logic this approach will not work for you. Also, why not just use public fields instead of properties? One reason would be that once you expose items as fields and other objects consume those fields you would be unable to change them to properties later, should you need to add validation logic, without having to also recompile the consumers.
Notice in the above example that I did not provide a constructor. This is something I would typically avoid in my own code but, often, when dealing with third party assemblies you may be faced with objects like this. To properly initialize the object you may set the properties after it has been created, like this:
public void foo()
{
DocumentInfo di = new DocumentInfo();
di.Path = "c:\\some folder\\somefile.txt";
di.DocumentId = 1;
}
A new feature in the framework, called object initializers, makes this initialization a bit more concise:
public void foo()
{
DocumentInfo di = new DocumentInfo(Path="c:\\some folder\\somefile.txt", DocumentId=1);
}
This, in my opinion, is clearly more concise than the previous example and provides a contructor-like syntax for dealing with third party tools that have, for whatever reason, not provided constructors for their objects.
For more information on automatic (auto-implemented) properties visit Auto-Implemented Properties (C# Programming Guide).
For more information on object intializers visit Object and Collection Initializers (C# Programming Guide).