How to create immutable objects in C# 6

In C#5 you would write a Person class with immutable properties with getters as follows:

public class Person
{
    private readonly string _name;
    private readonly int _age;

    public Person(string name, int age)
    {
        _name = name;
        _age = age;
    }

    public string Name
    {
        get
        {
            return _name;
        }
    }

    public int Age
    {
        get
        {
            return _age;
        }
    }
}

The readonly keyword will make sure that the private properties can only be assigned from the constructor. If try the following…

public int Age
{
    get
    {
        return _age;
    }
	set
	{
		_age = value;
	}
}

…you’ll get a compiler error:

“A readonly field cannot be assigned to (except in a constructor or a variable initializer)”

A more simple way to achieve the same might be the “private set” construction:

public class Person
{
	public int Age { get; private set; }
	public string Name { get; private set; }

	public Person(string name, int age)
        {
           Name = name;
           Age = age;
        }		
}

However, the Age and Name fields can still be modified within the Person class:

public string Greet()
{
	Name = "Jill";
	return string.Format("Hello from {0}", Name);
}

You’ll probably guess what the following will output:

static void Main(string[] args)
{
	Person p = new Person("John", 28);
	Console.WriteLine(p.Greet());

	Console.ReadKey();
}

That’s right, “Hello from Jill” which is a bit unexpected from the caller’s point of view.

C#6 comes to the rescue in the following form:

public class Person
{
	public int Age { get; }
	public string Name { get;}

	public Person(string name, int age)
	{
		Name = name;
		Age = age;
	}
}

The Age and Name fields can be set in the constructor but not anywhere else. The Greet() method will fail with the following compiler error:

“Property indexer ‘Person.Name’ cannot be assigned to — it is read only”

View all various C# language feature related posts here.

Advertisements

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

3 Responses to How to create immutable objects in C# 6

  1. maksymshysha says:

    Here is a Delphi style, how to manage accessibility of class propertes and methods. Used mostly in visual classes hierarchy. The idea is to use “implementation class” and “usage” class-descendant. This child class frequently contains only properties with tuned accessors.

    ///
    /// Base class to declare fields, properties and all methods.
    ///
    class CustomPerson
    {
    public string Name { get; private set; }
    public int Age { get; private set; }

    protected int Weight { get; set; }

    public CustomPerson(string name, int age)
    {
    Name = name;
    Age = age;

    Weight = 55;
    }
    }

    ///
    /// Child class to only restrict or expand visibility of properties and methods.
    ///
    public class Person : CustomPerson
    {
    public new int Weight { get { return base.Weight; } }

    public Person(string name, int age) : base(name, age)
    { }
    }

  2. Ivan says:

    Hi Andras,

    Have you tried doing C# 6 immutable objects with Entity Framework (6 or 7)? If EF can handle it, that’d be great news for DDD developers!

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

iReadable { }

.NET Tips & Tricks

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

Bite-size insight on Cyber Security for the not too technical.

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: