Hello,
How would you write a call to the .ToString() method on an object of type object that can be null. I currently do the following, but it's pretty long :
myobject == null ? null : myobject.ToString()
Hello,
How would you write a call to the .ToString() method on an object of type object that can be null. I currently do the following, but it's pretty long :
myobject == null ? null : myobject.ToString()
If you use that specific type frequently in this way you could write a method GetString(object foo)
which will return a string or null. This will save you some typing.
Is there something similar to C++ templates in C#? If yes, you could apply that to the GetString()
method, too.
One way to make the behaviour more encapsulated is to put it in an extension method:
public static class ObjectExtensions
{
public static string NullSafeToString(this object input)
{
return input == null ? null : input.ToString();
}
}
Then you can call NullSafeToString
on any object:
object myobject = null;
string temp = myobject.NullSafeToString();