Sunday, September 16, 2007

Asymmetric Accessor Accessibility in C#

Today I wanted to define one accessor with two different accessibility levels. That is, I wanted a property to have public 'get' access and private 'set' access. I remembered that in .NET 2.0 this became possible, but didn't remember exactly the syntax. So I tried first my intuition, which was:

public DataTable MyTable
{
get { return myTable; }
}

private DataTable MyTable
{
set { myTable = value; }
}

Unfortunately, I was wrong. A quick search revealed the secret syntax:

public DataTable MyTable
{
get { return myTable; }
private set { myTable = value; }
}

 


More details in the MSDN entry.

No comments: