Null propagation is a very nice feature - but where and how does the actual magic happen?
Where does frm?.Close()
get changed to if(frm != null) frm.Close();
- Does it actually get changed to that kind of code at all?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
Well, yes, but at the IL level, not the C# level. The compiler emits IL code that roughly translates to the equivalent C# code you mention.
It is done by the compiler. It doesn't change
frm?.Close()
toif(frm != null) frm.Close();
in terms of re-writing the source code, but it does emit IL bytecode which checks for null.Take the following example:
Compiles to:
Which can be read as:
call
- CallGetPerson()
- store the result on the stack.dup
- Push the value onto the call stack (again)brtrue.s
- Pop the top value of the stack. If it is true, or not-null (reference type), then branch toIL_000B
If the result is false (that is, the object is null)
pop
- Pops the stack (clear out the stack, we no longer need the value ofPerson
)ret
- ReturnsIf the value is true (that is, the object is not null)
call
- CallDoIt()
on the top-most value of the stack (currently the result ofGetPerson
).ret
- ReturnsManual null check:
Note that the above is not the same as
?.
, however the effective outcome of the check is the same.No null check: