Consider the following code that uses two slightly different methods to test _instance and assigns it if it is not already installed.
class InstantiationTest { private Object _instance; public void Method1() { if(_instance == null) { _instance = new Object(); } } public void Method2() { _instance = _instance ?? new Object(); } }
Either VS or Resharper continue to emphasize my explicit null checks and encourage me to refactor using the null-coalescing operator.
I wondered if the compiler is sufficient enough to detect the case in Method2() , where _instance reassigned to itself (effectively nop ?) And rewrite Method2() in Method1() .
I see that this is not the case:
Test.Method1: IL_0000: ldarg.0 IL_0001: ldfld UserQuery+Test._instance IL_0006: brtrue.s IL_0013 IL_0008: ldarg.0 IL_0009: newobj System.Object..ctor IL_000E: stfld UserQuery+Test._instance IL_0013: ret
vs:
Test.Method2: IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldfld UserQuery+Test._instance IL_0007: dup IL_0008: brtrue.s IL_0010 IL_000A: pop IL_000B: newobj System.Object..ctor IL_0010: stfld UserQuery+Test._instance IL_0015: ret
My question is why?
Is it difficult to implement at the compiler level too trivial to cost the implementation effort, or something that I am missing?
source share