Tuesday 22 July 2008

How do I have a public get and a private set for a property in C#.NET?

using System;

public class Person
{
private string name;

public string Name
{
get { return name; }
private set { name = value; }
}

public Person( string name )
{
Name = name;
}
}

You're probably thinking that the constructor could simply access the private member variable but I prefer to use properties for any interaction. It also means that you don't have to use the 'this' keyword if members and parameters have the same name:

this.name = name;

No comments: