IL ldsfld Instruction

Square abstract illustration

In addition to storing values in static fields, there exists an intermediate language instruction to load values from them. This is the ldsfld instruction—we look at it in this example.

This .NET IL example shows the ldsfld instruction. It provides the original C# program.

Example

This program first assigns the static field _a to the value 3; this is done with a stsfld instruction. Next, we need to load the value of _a for the if-statement. What happens is the ldsfld instruction pushes the value stored in the location of _a onto the top of the evaluation stack. Then, we load the constant 4 onto the top of the evaluation stack with the ldc.i4.4 instruction.

stsfld Instruction
Program that has ldsfld instruction [C#]

using System;

class Program
{
    static int _a;
    static void Main()
    {
	Program._a = 3;
	if (Program._a == 4)
	{
	    Console.WriteLine(true);
	}
    }
}

IL

.method private hidebysig static void  Main() cil managed
{
  .entrypoint
  // Code size       21 (0x15)
  .maxstack  8
  IL_0000:  ldc.i4.3
  IL_0001:  stsfld     int32 Program::_a
  IL_0006:  ldsfld     int32 Program::_a
  IL_000b:  ldc.i4.4
  IL_000c:  bne.un.s   IL_0014
  IL_000e:  ldc.i4.1
  IL_000f:  call       void [mscorlib]System.Console::WriteLine(bool)
  IL_0014:  ret
} // end of method Program::Main

Continuing on. Once the constant 4 and the value stored in the static field _a are at the top two places in the stack, we can use a branch statement (branch if not equal). This transfers control to the end of the method if the two are not equal. If they are equal, though, we reach the Console.WriteLine call. This corresponds to the if-block in the C# code.

Notes

Note

As with the stsfld instruction, you can improve performance by minimizing the occurrence of ldsfld instructions. This means you copy the value to a local variable and then use that instead. This is apparent in a field optimization I have demonstrated. Arrays also benefit.

Local Variable Field Optimization

Summary

We walked through a C# program and its intermediate representation. With the ldsfld (and the counterpart stsfld) we can load and store values using static references.

Intermediate Language
.NET