C#: Get and Set

This entry is part 71 of 71 in the series C#

A get and set example:

public class BaseClass 
{
	private string _name;
	public string Name
	{
		get 
		{
			return _name; 
		}
		set 
		{
			_name = value; 
		}
	}
}

public class DerivedClass : BaseClass 
{
	private string _name;
	public new string Name   // Notice the use of the new modifier
	{
		get 
		{
			return _name; 
		}
		set 
		{
			_name = value; 
		}
	}
}

public class MainClass 
{
	public static void Main() 
	{
		DerivedClass d1 = new DerivedClass();
		d1.Name = "John";  // Derived class property
		Console.WriteLine("Name in the derived class is: {0}",d1.Name);
		((BaseClass)d1).Name = "Mary"; // Base class property
		Console.WriteLine("Name in the base class is: {0}",
			((BaseClass)d1).Name);   
	}
}

getset

Series Navigation<< C#: Generic swap functions