WPF Basics – Different Between Public Variables and Public Property
Public variables can be accessed directly with the instance of the class. In this given example, _name and _city are the public variables.
Public properties are interface methods (like Get and Set Method in C++) for the private, protected and public variables. It can do more work rather than changing the value as it is a method. You can add notify event handler in the set methods.
A good C# class implementation will have private or protected variables with public properties to change the values.
public class StudentInformation
{
public string _name;
public string _city;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public string City
{
get
{
return _city;
}
set
{
_city = value;
}
}
public override string ToString()
{
return Name + " " + City;
}
}
|