string s = null; Console.WriteLine(Convert.ToString(s));//1 Console.WriteLine(s);//2 Console.WriteLine(s.ToString());//3 
  1. Why in the first case does not issue NULL reference?
  2. Why in the second case does not issue NULL reference? If I'm not mistaken, then in the Console.WriteLine () method, the .ToString () method is invoked to all variables explicitly.
  3. Why when explicitly specifying. ToString () returns a NULL reference?
    You can link on these issues or keywords to find the necessary information.

Here is the il-code of the program:

 IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: call string [mscorlib]System.Convert::ToString(string) IL_0009: call void [mscorlib]System.Console::WriteLine(string) IL_000e: nop IL_000f: ldloc.0 IL_0010: call void [mscorlib]System.Console::WriteLine(string) IL_0015: nop IL_0016: ldloc.0 IL_0017: callvirt instance string [mscorlib]System.Object::ToString() IL_001c: call void [mscorlib]System.Console::WriteLine(string) IL_0021: nop IL_0022: ret 

    1 answer 1

    Regarding null output through Console.WriteLine() , MSDN says :

    If value is null, only the line output terminator is written to the standard output stream.

    That is, Console.WriteLine(null) displays only one newline. This explains an example (2). In this case, Console.WriteLine according to the documentation, does not have the right to stupidly call ToString (especially since we caused an overload with the string, there is no need for conversion). In order to comply with the documentation, the function must check its argument to null . This can be seen directly in the source code of the current version of .NET :

     if (value==null) { WriteLine(); } else { ... 

    Further, according to the documentation for Convert.ToString(string s) , the value does not change:

    value is returned unchanged.

    Therefore, Convert.ToString(s) returns null , and the null output works without problems, as in the example (2). This explains the example (1).


    Finally, the example (3), the call to s.ToString() is a method call on a null link, which naturally leads to a NullReferenceException .