ShdNx
ShdNx

Reputation: 3213

IL: ldfld vs ldflda

I'm writing a small IL-weaving application using Mono.Cecil, that requires me to manipulate the target assembly on an IL level.

My question is quite simple, but I still find the matter very confusing. What is the practical difference between the ldfld and ldflda instructions?

I have consulted with msdn, and it appears that while ldfld fetches the value of the field, ldflda gets the address of the field. Okay... but what does this mean? I first thought that the former is used for value types (and string), and the latter for reference types, but I have compiled a C# snippet and checked it in Reflector, and it proved me wrong.

I haven't been able to find any distinct pattern in when the C# compiler emits ldflda instead of ldfld, and my searches didn't reveal any articles that would explain this. So when to use ldflda instead of ldfld?

Any help would be very much appreciated.

Upvotes: 8

Views: 3465

Answers (2)

If you pass a field to a subroutine as a ref parameter, you should see the compiler emit a ldflda for it in order to obtain the reference to pass in.

Upvotes: 1

Andrey
Andrey

Reputation: 60075

I guess it is used for structures:

struct Counter
{
   public int i;
}

struct Something
{
   public Counter c;
}

Something s;
s.c.i++;

I am pretty sure c here is loaded by address otherwise it would create a copy of Counter. That's why you can't do this with propery.

Upvotes: 9

Related Questions