Method 1
private int someVar;
public int SomeVar
{
get { return someVar; }
set { someVar= value; }
}
This method is generally, not preferred because some languages (such as VB.NET) are case insensitive. Therefore someVar
, SomeVar
, SOMEVAR
and somevar
as well as all possible combinations of upper and lower case you can think of mean the same to the compiler and this is likely to generate errors.
Method 2
public int SomeVar{get; set;}
This method, called automatic property implementation, creates a private variable in the shadows for storage and retrieval of the data passed to the property.
In VB.NET, the name of the variable created for each auto-implemented property is the same as the property prefixed with an underscore (_). So a property with name SomeProperty
will have a corresponding private variable called _SomeProperty
.
This can be demonstrated in your VB.NET code by creating any auto-implemented property and then creating a variable with the same name as the auto-implemented property prefixed with an underscore.
In C#, however, if you have an auto-implemented property, a variable decorated with the CompilerGenerated
attribute is used for the property. Thus, you can have the auto-implemented property and a variable with the same name as the property but in a different casing (as in Method 1).
Conclusion
It is generally preferred to use auto-implemented properties whenever possible. Where the need arises that you perform some validation before assigning the property to it's corresponding variable, it is recommended to use name the variable to which the property's value is stored with an underscore prefix as below.
private int _SomeVar;
public int SomeVar
{
get { return _SomeVar;}
set { _SomeVar = value > 0 ? value : 0; }
}