Dustin Davis
Dustin Davis

Reputation: 14585

stsfld vs stfld

Looking at the difference between the stfld and stsfld il op codes, the stfld has a null reference check while stsfld does not. Why is this? Is it because static fields are on the high-frequency heap and so they are not garbage collected?

http://msdn.microsoft.com/library/system.reflection.emit.opcodes.stfld.aspx

The stack transitional behavior, in sequential order, is:

  1. An object reference or pointer is pushed onto the stack.
  2. A value is pushed onto the stack.
  3. The value and the object reference/pointer are popped from the stack; the value of field in the object is replaced with the supplied value.

The stfld instruction replaces the value of a field of an object (type O) or via a pointer (type native int, &, or *) with a given value. Field is a metadata token that refers to a field member reference. The stfld instruction can have a prefix of either or both of Unaligned and Volatile.

NullReferenceException is thrown if the object reference or pointer is a null reference and the field isn't static.

MissingFieldException is thrown if field is not found in the metadata. This is typically checked when the Microsoft Intermediate Language (MSIL) instruction is converted to native code, not at runtime.

Upvotes: 3

Views: 2905

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063298

Static members never have a target instance. If there are parameters (on a method), arg0 refers to the first parameter, not the target instance (aka this). Since there is no target-instance, a null check is meaningless: there is nothing to dereference.

Upvotes: 7

Related Questions