What is the difference between prop and a full property?
Basic behavior and purpose of both of the property method is almost same. But the major difference is in the implementation. The difference between
public string Name{get;set;}
AND
private string _Name;
public string Name
{
get { return _Name; }
set { _Name=value; }
}
is if you use short property syntax (introduced in framework 3.0 or later), then the property sting is never initialized i.e. if you directly use "Name" property anywhere without setting the value to it, it will return a NULL value. But if you use second syntax to initialize the property value, it will return a EMPTY string because when you initialize a string, it is initialized with a EMPTY value not the NULL. So if you return the property value without initializing using FULL Property Method, it will always return the EMPTY string not the NULL value.
The only difference (other than the fact you would have to do the initialization with "Default Name" in your class constructor) is that _Name
will be visible within the class itself. There's a risk that the class will internally reference _Name
rather than Name
, everything will work fine, and at some later point in time you'll add some logic to Name
that will not be called because you're using _Name
within the class.
Example:
private string _Name = "Default Name";
public string Name
{
get { return _Name.Left(42); } // Changed the getter
set { _Name = value; }
}
void MyOtherMethod()
{
string foo = _Name; // Referencing the private field accidentally instead of the public property.
// Do something with foo
}