I'm an absolute beginner, you see. Say I have a string object on the stack and want to get the number of characters in it - its .Length property. How would I get the int32 number hidden inside?
Many thanks in advance!
I'm an absolute beginner, you see. Say I have a string object on the stack and want to get the number of characters in it - its .Length property. How would I get the int32 number hidden inside?
Many thanks in advance!
There's really no such thing as properties in IL. There are only fields and methods. The C# property construct is translated to get_PropertyName
and set_PropertyName
methods by the compiler, so you have to call these methods to access the property.
Sample (debug) IL for code
var s = "hello world";
var i = s.Length;
IL
.locals init ([0] string s,
[1] int32 i)
IL_0000: nop
IL_0001: ldstr "hello world"
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: callvirt instance int32 [mscorlib]System.String::get_Length()
IL_000d: stloc.1
As you can see the Length property is accessed via the call to get_Length
.
I cheated ... I took the following C# code and took a look at it in ildasm/Reflector
static void Main(string[] args)
{
string h = "hello world";
int i = h.Length;
}
is equivalent to
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
.maxstack 1
.locals init (
[0] string h,
[1] int32 i)
L_0000: nop
L_0001: ldstr "hello world"
L_0006: stloc.0
L_0007: ldloc.0
L_0008: callvirt instance int32 [mscorlib]System.String::get_Length()
L_000d: stloc.1
L_000e: ret
}