C#: get and set accessors

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

Consider the following program where the Employee class has a private string name.

If we declare an instance e1 in the Program class, we would not be able to access the private string using e1.name.

Accessors
using System;

namespace Automatic
{
    public class Employee
    {
        private string name;

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

    class Program
    {
        static void Main()
        {
            Employee e1 = new Employee();
            e1.Name = "John";  //This will set name to John
            Console.WriteLine(e1.Name);  //This will get the name
            Console.ReadLine();
        }
    }
}

However, in C# there are the get and set accessors where we can use them to access, in a way, the private properties of a class.

The get Accessor

The body of the get accessor is similar to that of a method. It must return a value of the property type.

The execution of the get accessor is equivalent to reading the value of the field.

The set Accessor

The set accessor is similar to a method that returns void.

It uses an implicit parameter called value, whose type is the type of the property.

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

 

Series Navigation<< C#: Scope and declaration space
C#: Automatic Properties >>