Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm reading Effective C# (Second Edition) and it talks about method inlining.

I understand the principle, but I don't see how it would work based on the 2 examples in the book. The book says:

Inlining means to substitute the body of a function for the function call.

Fair enough, so 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 might (will?) inline it to:

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

Now, with these two examples (verbatim 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 the code but doesn't go any further into how they might be inlined. How would the JIT compiler inline these 2 examples?

like image 208
Sergi Papaseit Avatar asked Mar 27 '11 22:03

Sergi Papaseit


2 Answers

Automatic properties are syntactic sugar for field-backed properties.

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

Hence the code you give is more or less equivalent to:

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 inlined to string val = Obj._name.

Likewise the code

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

Is is equivalent to:

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

Which can be inlined to:

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

Note that private and public apply to compilation, not to execution, so while the fact that the backing field is private would make Obj._name illegal outside of the class in question, the equivalent code produced by inlining, is allowed.

like image 165
Jon Hanna Avatar answered Oct 12 '22 15:10

Jon Hanna


Hypothetically speaking, inlining here would unwrap the body of get_Name() that's auto-generated by the compiler, which simply returns a private backing field. It might look something like this:

string val = Obj.k__BackingField;
like image 41
Rex M Avatar answered Oct 12 '22 13:10

Rex M