Sie sind auf Seite 1von 9

C# Immutability and its future

In this article, we will learn:


What is Immutability?
Why do we like Immutability?
What is Immutability in C#?
Benefits of Immutability
C# Evolution in terms of Immutability
Limitations of Immutability
The future C#7

What is Immutability?
Immutability is an active programming where we dont modify anything that exists and it
does not have any side effects.
So lets see what is mutable and what is the issues with it?

1
2
3
4
5
6
7
8
9
1
0
1

using System;
using SYstem.Text;
public sealed class Mutable
{
public int value {get; set;}
}
public class UsageOfMutable
{
public static void main()
{
var m = new Mutable();

1
1
2
1
m.Value = 20;
3
m.Value = 30;
1
}
4
}
1
5
1
6

In the above example, we have a Mutable class. It is mutable because we can make
changes to it. This is there since C#3.0
Lets write it in C#6.0.

1
2
3
4
5
6
7
8
9
1
0
1
1
1
2
1
3
1
4
1
5
1
6
1
7
1
8
1
9
2
0
2
1
2
2
2

using System;
using System.Text;
public sealed class Mutable
{
public int value {get;}
public StringBuilder NameBuilder { get; }
public Mutable(int Value, StringBuilder NameBuilder)
{
Value = value;
NameBuilder = nameBuilder;
}
}
public class UsageOfMutable
{
public static void main()
{
StrinBuilder test = new StrinBuilder();
var m = new Mutable(10,test);
test.Append("foo");
m.NameBuilder("bar");
Console.WriteLine(m.NameBuilder);
}
}

3
2
4
2
5

The output for above program will be foobar.

What are the problems with mutable data structure?

If you are not sure whether your data is changed then it is difficult to code

If you need to look at the method and the calling methods then it is difficult to follow
the flow

Following and debugging code becomes more difficult, if you are working in
multithreaded environment

What is immutability in C#?


Immutability means once the variable is bound to certein values you cant modify that
variable.
Example:

1
2 namespace ImmutableExample
3 {
4 class ImmutableProgram
5 {
6 static const int MAX = 100;
7
public static void main()
8
{
9
Console.WriteLine(MAX);
1
}
0 }
1 }
1

This will print the output: 100


We cant modify the value of MAX at any given time. The const means it is a compile time
constant and we can not modify the value.

1
2
3
4
namespace ImmutableExample
5
{
6
class ImmutableProgram
7
{
8
const int MAX = 100;
9
readonly int value;
1
public ImmutableProgram(int thevalue)
0
{
1
value = thevalue;
1
}
1
public static void main()
2
{
1
Console.WriteLine(MAX);
3
}
1
}
4
}
1
5
1
6

This will also print 100 and you cant change the value at any time.
readonly can take a value and bound the value only once.
But if you will try to change the value like below program, then you will get compilation error.

1 namespace ImmutableExample
2 {
3 class ImmutableProgram
4 {
5 const int MAX = 100;
6 readonly int value;
7
public ImmutableProgram(int thevalue)
8
{
9
value = thevalue;
1
}
0
public void foo()
1
{
1
value = 10;
1
}
2
public static void main()

1
3
1
4
1
5
1
6
1
7
}
1
8
1
9
2
0

{
Console.WriteLine(MAX);
}
}

Benefits of Immutability :

In Immutability, we need to validate its code contracts only once, in the constructor.

Objects are automatically thread-safe.Immutable objects are particularly useful in


concurrent applications. Since they cannot change state, they cannot be corrupted
by thread interference or observed in an inconsistent state

No defensive copying

Easier to reason about code as theres no need to step into the methods for making
sure they dont change anything.

C# Evolution in terms of Immutability :


C#1.0:

Value types

Immutable string types and StringBuilder

Unsealed by default

Propert get/set with single access

C#2.0:

public string Name { get; private set; }

C#3.0:

Anonymous types

LINQ

Object and collection initializers

C#4.0:

Optional parameters and named arguments

C#5.0:

<tumbleweed>

C#6.0:

Read-only autoprops

Default values for autoprops

Expression-bodied members encourage feeling of Immutability

Lets look at an example in C#6.0.


Below is the Data model that we will be using in example:
Person
-name
-Address
-Phone numbers
-Friends
Address
-Street
-city
Phone Number:(Enum)
-Number
-Type
Number Type:
-Home,Mobile,Phone
PhoneNumberType Enum:

1 public enum PhoneNumberType


2{
3 Mobile = 0,
4 Home = 1,
5 Work = 2
6}

Address class:

1
2
3
4
5
6
7
public sealed class Address
8
{
9
public string Street { get; }
1
public string City{ get; }
0
1
private Address(Builder builder)
1
{
1
Street = builder.Street;
2
City = builder.Cityl
1
}
3
1
public sealed class Builder
4
{
1
public string Street { get; set; }
5
public string City{ get; set; }
1
6
public Address Build()
1
{
7
return new Address(this);
1
}
8
}
1
}
9
2
0
2
1
2
2

Person Class:

1
2
3
4
5
6
7
8
9
1
0
1
1
1
2
1
3
1
4
1
5
1
6
1
7
1
8
1
9
2
0
2
1
2
2
2
3
2
4
2
5
2
6
2
7
2
8

using System.Collections.Generic;
using System.Collections.Immutable;
public sealed class Person
{
public string Name { get; }
public Address Address { get; }
public IImutableList<PhoneNumbers> Phones { get; }
private Person(Builder builder)
{
Name = builder.Name;
Address = builder.Address;
Phones =Phones.ToImmutableList();
}
public sealed class Builder
{
public string Name { get; set; }
public Address Address { get; set; }
public List<PhoneNumber> Phones { get; } = new List<PhoneNumber>();
public Person Build()
{
return new Person(this);
}
}
}

Program.cs:

1 class Program
2{
3 static void Main(string[] args)
4 {
5 Name = "Steve",
6 Address = new Address.Builder { city = "Reading", Street = "... "}.Build(),
7 Phone = {}
8 }.Build();
9}

Limitations of Immutability:
If your object is quite big, necessity to create a copy of it with every single change may hit
the performance of your application

Necessity to create a copy of your object with every single change may hit the
performance of your application

The Future : C#7

Record Types

Static analysis

More in the BCL

More memory model details etc..

We will discuss on potential features in C# 7 in next article.


Thanks for visiting !!

Das könnte Ihnen auch gefallen