How does the inlining method work for auto properties in C #?

I am reading Effective C # (second edition) and it talks about introducing a method.

I understand the principle, but I do not understand how it will work based on two examples in the book. The book says:

Nesting means replacing a function body with a function call.

This is true, therefore, if I have a method and its call:

public string SayHiTo(string name) { return "Hi " + name; } public void Welcome() { var msg = SayHiTo("Sergi"); } 

The JIT compiler can (will?) Embed it in:

 public void Welcome() { var msg = "Hi " + "Sergi"; } 

Now, with these two examples (literally from the book):

Example 1

 // readonly name property public string Name { get; private set; } // access: string val = Obj.Name; 

Example 2

 string val = "Default Name"; if(Obj != null) val = Obj.Name; 

The book mentions code, but does not go further about how they can be embedded. How did the JIT compiler introduce these 2 examples?

+7
source share
3 answers

Automatic properties are syntactic sugar for properties supported by fields.

Properties are syntactic sugar for setter and / or getter methods.

Therefore, the code you give is more or less equivalent:

 private string _name; public string get_Name() { return _name; } private void set_Name(string value) { _name = value; } 

Then string val = Obj.Name becomes equivalent to string val = Obj.get_Name() , which can be attached to string val = Obj._name .

Similar code

 string val = "Default Name"; if(Obj != null) val = Obj.Name; 

Is equivalent to:

 string val = "Default Name"; if(Obj != null) val = Obj.get_Name(); 

What can be attached to:

 string val = "Default Name"; if(Obj != null) val = Obj._name; 

Please note that private and public apply to compilation, not execution, therefore, if the fact that the support field is private will make Obj._name illegal outside the class in question, the equivalent code created by the attachment is allowed.

+6
source

Hypothetically speaking, the attachment here will expand the body of get_Name() , which is automatically generated by the compiler, which simply returns a private support field. It might look something like this:

 string val = Obj.k__BackingField; 
+4
source

The insert takes after checking availability , so it can optimize the code so that you cannot with a simple replacement of the source code.

+2
source

All Articles