Read-only member and constructor initialization in C#

Read-only member in C#

There are times when we want to create a Person object with firstname and lastname and then ensure that the names are not changeable. Here’s one way of creating read-only member.

read-only member in C#

class Person
{
  // create class members that are read only
  private readonly string _firstname;
  private readonly string _lastname;

  // read only members can only be modified from the constructor
  // this helps developers working on the class to avoid changing
  // information about the person 
  public Person(string firstname, string lastname)
  {
    _firstname = firstname;
    _lastname = lastname;
  }

}

Read only member are not changeable by class methods. Only the constructor can change it. The member truly becomes read only after the construction finishes.