tags:

views:

216

answers:

2

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()
+2  A: 

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.

mxp
I use it frequetnly but from differnt part of the wall projet, so I would nee a call to something like Tools.GetString(). That be better. But is there a syntax that do not need to call a method ?
Toto
+10  A: 

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();
Fredrik Mörk
So with extension methosd, you can call methods on null references ! Weird but it solve my issue !
Toto
Well as potentially you do not know whether converting null object to null string appropriate in all cases i think it is reasonable to add an overload that takes default value.
Dzmitry Huba
@Duaner: it's not as weird as it looks like; it's just syntactic sugar. The call `myobject.NullSafeToString()` in my sample will be translated by the compiler into `ObjectExtensions.NullSafeToString(myobject)`.
Fredrik Mörk