What is the magic that makes properties work with the CLR?

I noticed that when I reflect on the assembly, calls to access properties sometimes look like methods

// "Reflected" example class Class1 { public bool Boolean { get; set;} } class Class2 { public Class2() { var class1 = new Class1(); var boolean = class1.get_Boolean(); } } 

Now I was curious, and I put a method with a similar signature in Class1 , which looks like a standard agreement for accessories.

 // "Hacked" example class Class1 { public bool get_Boolean() { return true; } } 

Somehow, the C # compiler still considers get_Boolean as a method.

What magic sauce get method as a property?

+8
c # clr syntactic-sugar
source share
2 answers

If you look at IL, you will find something like this:

 .property instance string Source() { .get instance string System.Exception::get_Source() .set instance void System.Exception::set_Source(string) } .method public hidebysig specialname newslot virtual instance string get_Source () cil managed { ... } .method public hidebysig specialname newslot virtual instance void set_Source ( string 'value' ) cil managed { ... } 

So, β€œmagic” is a .property member that glues the two methods together.

+7
source share

The .NET assembly not only contains code, but also contains metadata that describes the code.

In the case of a method, metadata is generated that describes the name of the method, signature, etc.

In the case of property X it is compiled as a bunch of access methods ( get_X and / or set_X ), and metadata of the usual method is generated for each of them. Then additional metadata is generated that indicates that all these access methods actually belong to each other as one logical object (property).

Now back to your example: if you define a method called get_Boolean using C #, the C # compiler will only emit method metadata, but no additional property metadata. Essentially, the compiler chooses which metadata to emit. And since you did not use the C # syntax for the property, but the method declaration syntax, what the C # compiler will generate metadata for.

Metadata is described in detail in the ECMA 335 standard , which describes the CLI platform (.NET). See the section in chapter II.22.34 on page 241 for an explanation of how property metadata works.

+7
source share

All Articles