can somebody tell me the difference between
public class Vendor
{
public string VendorName { get; set; }
}
and
public class Vendor
{
private string vendorName = string.Empty;
public string VendorName
{
get { return vendorName; }
set { vendorName = value; }
}
}
Is there any benefit of using a private variable? Doing so is only wastage of time and lines? There are no manipulations done to the property within the class.
Thanks
C# 3 introduced auto-implemented properties, which makes your first snippet possible. The compiler is going to create your backing field for you, which would make the compiled code equivalent to the compiled code of your second snippet. If you’re working in a <= 2.0 code base, you’ll be using the second snippet.
The benefit of using a private variable would be if you performed some sort of validation when the property is set, such as restricting integers to positive values or rejecting null strings. If you do not need such behavior or simply wish to handle those activities elsewhere and the property is just a fetch and set, then use the auto-implemented version.