Creating an Immutable Class

To create an immutable class in c#, we have to do the following points:

1.    Set accessors as private.

Now question is what are accessors ?

Accessors are nothing but are special method, and are used if they are public data members.

Accessors are commonly known as properties in term of programming language. A property is one or two more code blocks,representing two accessors get and set .Get accessor is used , when property is read, set accessor is used to set the new value of property.

Example of accessors in a class:

Class CsharpCorner
{
    Public string MemberName
    {
         get{ return MemberName ;}
          set{ MemberName = value;}
     }
}

You make the class immutable by declaring the set accessor as private. However, when you declare a private set accessor , you cannot use an object initializer to initialize the property. You must use a constructor or a factory method.

2. When we declare a set accessor as private, then we can’t initialize it by using object. We must use constructor for that purpose.

Example

Class CsharpCorner
{
     Public CsharpCorner (string name)
     {
          name = MemberName;
      }
     Public string MemberName
     {
          get{ return MemberName ;}
          private set{ MemberName = value;}
      }
}
Public class MainProgram
{
     Public static void main()
     {
          String nameofMember = “Ashish”;
          CsharpCorner csharp = new CsharpCorner(nameofMember);
      }
}

Our Immutable class is ready, and by doing this we are not allowing compiler to access fields directly.

Thanks for now.

Ebook Download
View all
Learn
View all