Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CLR question. Why method overloading in C# decides that null is a string? [duplicate]

Tags:

c#

clr

Possible Duplicate:
C#: Passing null to overloaded method - which method is called?

Here is a test case

object a = null;
var b = Convert.ToString (null);
var c = Convert.ToString (a);
string d = Convert.ToString (null); // CLR chooses Convert.ToString(string value)
string e = Convert.ToString (a); // CLR chooses Convert.ToString(object value)

The question is why CLR decides that null is interpreted as string in first case? It appears that this question was already answered here

Here is another similar case. None of these ifs are triggered

object x = null;
if (x is object)
{
    Console.Write ("x is object");
}

if (x is string)
{
    Console.Write ("x is string");
}

if (null is object)
{
    Console.Write ("null is object");
}

if (null is string)
{
    Console.Write ("null is string");
}
like image 769
Sergej Andrejev Avatar asked Oct 29 '09 05:10

Sergej Andrejev


People also ask

Why method overloading is needed in any programming language?

Method Overloading in Java is one of the most useful features of an Object-Oriented Language. It allows a class to have multiple methods with the same name. The only difference that these methods have is the different list of parameters that are passed through these methods.

At what time method overloading happens?

Method overloading is an example of static binding where binding of method call to its definition happens at Compile time.

Does return type matter in method overloading in C#?

The compiler does not consider the return type while differentiating the overloaded method. But you cannot declare two methods with the same signature and different return type. It will throw a compile-time error. If both methods have the same parameter types, but different return type, then it is not possible.

Why do we need method overloading in C#?

If we try to define more than one method with the same name and the same number of arguments then the compiler will throw an error. The advantage of method overloading is that it increases code readability and maintainability.


1 Answers

The answer is because it must choose a reference type (null doesn't work for value types), and every string is an object, but not every object is a string. See Jon Skeet's answer to this question for more information.

In response to your second example, if a variable that is null is passed to is, it will always evaluate to false, no matter what.

like image 119
Matthew Scharley Avatar answered Nov 03 '22 21:11

Matthew Scharley