Use and Advantage :private set

Basically, I want to create an instanceof a class, and once the instance is created, the properties of that object should not be allowed to be modified.

Bit tricky, when you hear this for the first time.

It can be achieved through private setter as follows.
Create the instance of the class using the constructor, and initialize the members through it.

Here is the solution:

public class Program
public static void Main()
Example ab = new Example("Gokul");
//ab.Name="ram"; Compiler Error

public class Example
public string Name { get; private set; }

// Constructor
public Example(string name) {
Name = name;

public void SayHi() {
Console.WriteLine(" Hi " + Name);

Thanks for reading.


About Gokul Dahal, Nepal

Software Engineer, Freelancer, Design and Develop web applications,Software Developer Nepal, FreeLancer Nepal Contact :
This entry was posted in C#. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s