M
Michael C
If we have something like this
object x = null;
MessageBox.Show(x.ToString())
we get an error. That kindof makes sense but there is no reason the
behaviour couldn't be to return an empty string. When we call x.ToString we
are really calling a function like this:
class Object
{
public static string ToString(object* Instance)
{
//code to convert the object pointer to a string
}
}
Why can't the compiler just pass in Instance as a null and let the code sort
it out. If the code wants to throw an error then it can but if it wants to
do something more useful then it can. This would be useful in some cases (I
admit they are rare but the ToString example above could potentially be used
quite often). I can think of a few cases where this could be useful, eg:
string x = null;
MessageBox.Show(x.IsNullOrEmpty.ToString())
MessageBox.Show(x.Length.ToString()) //<--- shows zero
DateTime? y;
MessageBox.Show(y.IsValid)
The interesting thing is you can define extention methods that do work on
null objects, eg
static class Extensions
{
public static bool IsSomething(this string s)
{
return !string.IsNullOrEmpty(s);
}
public static string ToStringIgnoreNull(this object s)
{
if(s == null) return string.Empty;
return s.ToString();
}
}
Then use it like this:
string x = null;
if (x.IsSomething()) MessageBox.Show(x)
or
object x = null;
MessageBox.Show(x.ToStringIgnoreNull())
Any comments?
Cheers,
Michael
object x = null;
MessageBox.Show(x.ToString())
we get an error. That kindof makes sense but there is no reason the
behaviour couldn't be to return an empty string. When we call x.ToString we
are really calling a function like this:
class Object
{
public static string ToString(object* Instance)
{
//code to convert the object pointer to a string
}
}
Why can't the compiler just pass in Instance as a null and let the code sort
it out. If the code wants to throw an error then it can but if it wants to
do something more useful then it can. This would be useful in some cases (I
admit they are rare but the ToString example above could potentially be used
quite often). I can think of a few cases where this could be useful, eg:
string x = null;
MessageBox.Show(x.IsNullOrEmpty.ToString())
MessageBox.Show(x.Length.ToString()) //<--- shows zero
DateTime? y;
MessageBox.Show(y.IsValid)
The interesting thing is you can define extention methods that do work on
null objects, eg
static class Extensions
{
public static bool IsSomething(this string s)
{
return !string.IsNullOrEmpty(s);
}
public static string ToStringIgnoreNull(this object s)
{
if(s == null) return string.Empty;
return s.ToString();
}
}
Then use it like this:
string x = null;
if (x.IsSomething()) MessageBox.Show(x)
or
object x = null;
MessageBox.Show(x.ToStringIgnoreNull())
Any comments?
Cheers,
Michael