Alex Rivera | Logout

Immutable objects with object initialisers

Asked 2009-08-20T05:39:08.033
13

I have the following attempt at an immutable object:

class MyObject
{
    private static int nextId;

    public MyObject()
    {
        _id = ++nextId;
    }

    private int _id;
    public int Id { get { return _id; } }
    public string Name { get; private set; }
}

Then, I try to use it like so:

MyObject o1 = new MyObject { Name = "foo" };

But the object initialiser fails because Name's setter is private. Is there a way around this, or do I have to choose between one or the other?

c#
Edit
Report

2 Answers

8

You need to set the property in the constructor, and you don't need a separate local variable for the id:

class MyObject {

   private static int nextId = 0;

   public MyObject(string name) {
      Id = ++nextId;
      Name = name;
   }

   public int Id { get; private set; }
   public string Name { get; private set; }
}

Creation:

MyObject o1 = new MyObject("foo");
answered 2009-08-20T05:45:50.297
3

You cannot use object initializers and have an immutable object, as object initializers require the property setters to be public. Public setters mean it will not be immutable.

The only way around that would be to simulate immutability, by throwing exceptions in the property setter after they have already been called once.

Personally I don't think that would be a good design, and I would question why you are so keen on using object initializers, instead of constructors. The syntax is almost identical.

answered 2009-08-20T05:46:01.607

Your Answer