I have a query about type of null.
I have a small program can anyone tell me about this.
public class TestApplication
{
public void ShowText(object ob)
{
Console.Write("Inside object");
}
public void ShowText(string str)
{
Console.Write("Inside string");
}
public void ShowText(int i)
{
Console.Write("Inside int.");
}
public void ShowText(char c)
{
Console.Write("Inside Character");
}
static void Main(string[] args)
{
new TestApplication().ShowText(null);
Console.Read();
}
}
Why it call the string function.
Is it means the type of null is string.
It might look a foolish conclusion but I am not able to find the region why it is calling the function of string.
Your question about the type of the null literal is answered here: What is the type of null literal?
But that doesn’t really matter when talking about overload resolution. The actual null value itself will automatically be converted to whatever type it ends up as.
As for why the
stringoverload is called:You can’t pass null as
intandcharparameters as they’re value types, so those two overloads are out. (They could have been candidates had you made them nullableint?andchar?types, but I won’t go into that.)Between the two other overloads taking reference types,
stringis a more specific type thanobject. That is, it derives from (and is therefore implicitly convertible to)object. Further, from the following section in the C# language spec (emphasis mine):Thus, the
stringoverload is chosen as the best fit.