Say in front
About C # code Convert.tochar (null); An exception occurred, and object obj = null; Convert.tochar (obj);//Returns an explanation of the empty character problem.
Why do you think of that?
Today, under the Bole feature, the article "about System.Convert" raises this question:
Convert.tochar (NULL);
This is called directly, and an exception is generated when executed;
And the following code does not show an exception!
Object obj = null; Convert.tochar (obj);//return ' \ n ' null character
Anomaly Analysis
System.ArgumentNullException happened.
To view the details, you can see the specific information for the exception, which is an exception in System.Convert.ToChar (String value, IFormatProvider provider):
But through the call stack, we can understand the error more clearly;
For example, there is a layer of calls between the methods in which the exception occurred:
System.Convert.ToChar (String value)
System.Convert.ToChar (string value), which is the key to the problem!
When Convert.tochar (obj) is executed, the type of obj is already defined as the object type, so the invocation is Convert.tochar (object value);
public static char ToChar (object value) { if (value! = null) { return (iconvertible) value). ToChar (null); } Return ' n ';}
Instead of executing convert.tochar (NULL), NULL can be assigned to multiple data types, and the compiler treats it as a string by default, so we see a middle step in the call stack: System.Convert.ToChar ( String value), implemented as follows:
public static char ToChar (string value) { return ToChar (value, null);}
That's why an exception occurred in System.Convert.ToChar (String value, IFormatProvider provider)
public static char ToChar (string value, IFormatProvider provider) { if (value = = null) { throw new Argumentnul Lexception ("value"); } if (value. Length! = 1) { throw new FormatException (environment.getresourcestring ("Format_needsinglechar")); } return value[0];}
Summarize
The reason for this is that the compiler gives the default data type of "null" to the problem, so it results in seemingly identical code, but produces a different result.
This also involves polymorphism and overloading (polymorphism is a feature of object-oriented programming thinking, overloading refers to the method can be based on the number of different parameters and types, to achieve a variety of functions, the overloaded method can be understood as the specific manifestation of polymorphism), if only Convert.tochar (object value); This kind of realization, also does not have the question which this article elaborated, also does not have the article.