0

Is there a more concise way of writing

string aString = someObj == null ? null : someObj.ToString();

i.e. if someObj is a null reference then return a null string, otherwise call ToString() on the object and return that?

Convert.ToString() doesn't help because it returns String.Empty(); I'm passing the result to an XML serializer and I want there to be no element if the object is null, not an empty one.

Rob Gilliam
  • 2,680
  • 4
  • 26
  • 29
  • 2
    See both Jon Skeet and Eric Lippert's answers at http://stackoverflow.com/questions/2929836/is-there-an-opposite-to-the-null-coalescing-operator-in-any-language – Ben Allred Jan 20 '14 at 16:40

4 Answers4

7

Your code is pretty simple. If you wish to reduce the amount of code because you must write the same fragment a lot of times, you could put the code into an extension method:

static class SomeObjExtensions {
    public static string ToStringWithNull(this object someObj) {
        return someObj == null ? null : someObj.ToString();
    }
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

You could create an extension method that describes the action,

public static class ObjectExtensions
{
    public static string ToStringOrNull(this object o)
    {
        return o == null ? null : o.ToString();
    }
} 

And use it as,

var aString = o.ToStringOrNull();
rae1
  • 6,066
  • 4
  • 27
  • 48
1

There is no such C# feature but probably it will be and can be called monadic null checking with ?. syntax, as described in probable C# 6.0 features article:

string aString = someObj?.ToString();
Konrad Kokosa
  • 16,563
  • 2
  • 36
  • 58
  • Accepting this answer as it tells the truth of the current situation while offering hope for a brighter future to come :-) – Rob Gilliam Jan 20 '14 at 22:57
-4
if(someObject == null) {
return null;
} else {
return someObject.ToString();
}

Yours is concise as it can get.

iefpw
  • 6,816
  • 15
  • 55
  • 79