What are the advantages and differences between the below two coding styles…
public void HelloWorld () {
private string _hello;
public string Hello {
get
{
return _hello;
}
set
{
_hello = value;
}
}
}
or
public void HelloWorld () {
public string Hello { get; set; }
}
My preference is for short simple code, but interested to hear opinions as I see many developers who insist on the long route.
The first one allows you to customize the accessors. For instance, you might want to validate the value in the setter, or lazily load the value in the getter. It also allows you to make the backing field
readonly.The second form allows no customization (except accessibility of the getter and setter). It’s just a shorthand equivalent of the first form.
If you don’t need to do anything specific in the getter and setter, the second form is usually more convenient.