One of the issues with properties in C#1.x is that the get and the set accessors get the same accessibility. In some situations you'd want to impose more usage restriction on the set accessor then on get . In the following sample both the get and set are public.
class Employee{ private string m_name; public string Name { get { return m_name; } set { m_name = value; } }}class Program{ static void Main(string[] args) { Employee emp = new Employee(); emp.Name = "Abhinaba Basu"; }}
class
{
}
emp.Name =
In case you want set to be more restricted than get you have no direct way of getting it done in C#1.x (other than splitting them into different properties). In C# 2.0 its possible to have different accessibility on get and set accessors using accessor-modifier. The following code gives protected access to set and public to get
class Employee{ private string m_name; public string Name { get { return m_name; } protected set { m_name = value; } }}class Program{ static void Main(string[] args) { Employee emp = new Employee(); emp.Name = "Abhinaba Basu"; // Will fail to compile }}
class Program
This is really cool because in many designs I have felt the need to make set accessor protected and allow get to be internal or public. With this addition to C# this becomes easy to do.
There are however lot of gotchas and cases to consider before going ahead and blindly using this. I have listed some which I found need to be considered....
Be sure to check the C# spec before using this feature as there are some subtleties specially in terms of member lookup....