2

I write tons of immutable types following this pattern:

class A 
{
  private readonly SomeType b;

  public A(SomeType b)
  {
    this.b = b;
  }

  public SomeType B
  {
    get {return b; }
  }
}

Is it possible to replicate this pattern using auto-properties? The closes I could get to is:

class A 
{
  public A(SomeType b)
  {
    B = b;
  }

  public SomeType B
  {
    get; private set;
  }
}

But it is not really satisfactory, as it doesn't guarantee that the reference to B is not going to change (we lost the readonly effectively). Is it possible to do better than that?

Grzenio
  • 35,875
  • 47
  • 158
  • 240
  • Not using auto-properties, and other than `readonly` or `const` there are no other keywords that enforce immutability in C#. The best you can do is block change from outside and enforce no change from within. Roslyn might be able to help in future by doing checks on the code for changes, but again this isn't built in by default. – Adam Houldsworth Dec 20 '13 at 11:01

1 Answers1

1

It's not possible to get any better than this with the current version of C#. However, this blog post mentioned a possible new feature in C# 6 discussed by the C# design team at a recent conference - readonly auto properties, which is exactly what you were after.

public int X { get; } = x;  
Richard
  • 29,854
  • 11
  • 77
  • 120