I had an issue related to System.Convert(Object value)
method, my research led me to this documentation.
I am wondering what are the reasons
behind this decision that c# team has made, because this doesn't make any sense to me.
From my point of view its better to return "Null", please pay attention to this example:
static void Main(string[] args)
{
int? ID = null;
string result = Convert.ToString(ID);
Console.WriteLine("{0} ,{1}",result ,result.Length);
Console.ReadKey();
}
//result would be "" and the result.Length=0
As you can see ID
is null
but convert(ID)
is not null
and it sounds weird to me !!
This is source code of convert(object value)
I picked it up from this answer of the question.
public static string ToString(Object value) {return ToString(value,null);}
public static string ToString(Object value, IFormatProvider provider) {
IConvertible ic = value as IConvertible;
if (ic != null)
return ic.ToString(provider);
IFormattable formattable = value as IFormattable;
if (formattable != null)
return formattable.ToString(null, provider);
return value == null? String.Empty: value.ToString();
Please pay attention to the last line
. I just want to know what is the rational
behind that.
Thank you in advance.
Edit
There are so many cases that ID.Tostring()
is not useful at all
for example :
public System.Web.Mvc.ActionResult MyAction(int? Id)
{
//This line of code dosent show "Id has no value" at all
MyContetnt = (System.Convert.ToString(Id) ?? "Id has no value");
return Content(MyContetnt);
}
In this code example, If you run this Mvc sample through this path :
http://localhost: portnumber/ControllerName/MyAction
I mean without using ID in the path
You see Nothing on the screen because ID
is null
here and the resault of Convert.Tostring(ID)
is System.Empty
or "" .
I mean in this case there is no way to refactor this code using null-coalescing-operator
, By using ID.tostring()
a nullrefrenceException
would be raised,That is not useful and is not my intention. I know that its easy to say :
MyContent = Id.HasValue ? Id.Value.ToString() : "Id has no value"
// this line works fine;
But suppose that The result of convert.ToString(Null)
was Null
Then the first code featured with null-coalescing-operator
would work perfectly.
so I am just curious that what is the reason behind this idea that the result of Convert.tostring (object null)
is string.empty
not null
?