Reputation: 658
I have created a console application to analyze the behavior of
Convert.ToString()
, i know Convert.ToString()
do not cause exception, but in terms of object it initialize the return string as empty, however in case of string it remains null.
string s = null;
object obj = null;
string objec = Convert.ToString(obj);//it return an empty string
string ss = Convert.ToString(s);// it returns ss=null
Upvotes: 1
Views: 108
Reputation: 4703
When you look at their compiled assemblies the program looks like this
string s = null;
Convert.ToString(null); //1
Convert.ToString(s); // 2
the first ToString
Returns ""
string because it checks the following condition
if (value == null)
{
return string.Empty;
}
and the second ToString
returns null because it executes following method
public static string ToString(string value)
{
return value;
}
it looks confusing because ToString
is same on both statements but actually they both are working differently. The first ToString
function calls the ToSting of Object Type
and the second ToString
function calls ToString of String Type
Upvotes: 2