Assignment of readonly property in initializer list

Can I tell you why it compiles?

namespace ManagedConsoleSketchbook { public interface IMyInterface { int IntfProp { get; set; } } public class MyClass { private IMyInterface field = null; public IMyInterface Property { get { return field; } } } public class Program { public static void Method(MyClass @class) { Console.WriteLine(@class.Property.IntfProp.ToString()); } public static void Main(string[] args) { // ************ // *** Here *** // ************ // Assignment to read-only property? wth? Method(new MyClass { Property = { IntfProp = 5 }}); } } } 
+3
source share
3 answers

This is an initializer of nested objects. It is described in the C # 4 specification as follows:

The initializer of the element that indicates the initializer of the object after the equal sign is the initializer of the nested object, that is, the initialization of the embedded object. Instead of assigning a new value to a field or property, assignments in the initializer of nested objects are treated as assignments to members of a field or property. Initializers of nested objects cannot be applied to properties with a value type or to read-only fields with a type value.

So this code:

 MyClass foo = new MyClass { Property = { IntfProp = 5 }}; 

will be equivalent to:

 MyClass tmp = new MyClass(); // Call the *getter* of Property, but the *setter* of IntfProp tmp.Property.IntfProp = 5; MyClass foo = tmp; 
+10
source

Since you are using an initializer that uses the ItfProp installer, not the Property installer.

Thus, at runtime, it will throw a NullReferenceException , since Property will be null .

+2
source

Because

 int IntfProp { get; set; } 

not readonly.

You did not call the installer MyClass.Property , just getter.

0
source

Source: https://habr.com/ru/post/1276050/


All Articles