-2

I came over a weird behavior of C# compiler. Can you elaborate why this code just works fine?

public class A
{
  public void Test()
  {
    var x = new B
    {
      // assigning to a read only property
      ReadOnlyProperty = {new KeyValuePair<int, int>(1, 1)}
    };           
  }
}

class B
{
  public IDictionary<int,int> ReadOnlyProperty { get; }
}

The expected behavior is not being able to assign anything to readonly properties.

LarsTech
  • 80,625
  • 14
  • 153
  • 225
Ehsan Mirsaeedi
  • 6,924
  • 1
  • 41
  • 46

1 Answers1

3

This is not an assignment, it's a collection initializer. The statement in your ctor is equivalent to the following code:

var x = new B();
x.ReadOnlyProperty.Add(new KeyValuePair<int, int>(1, 1));

Thus, you're only getting the property (and manipulating the instance), not setting it. Keep in mind that readonly does not prevent you from changing the state of an object; only that you cannot assign to that field outside the ctor and its initializer.

Joey
  • 344,408
  • 85
  • 689
  • 683