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.

1

4 Answers 4

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();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Wondering if ToStringOrNull conveys the meaning better?
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();

1 Comment

Accepting this answer as it tells the truth of the current situation while offering hope for a brighter future to come :-)
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();

Comments

-4
if(someObject == null) {
return null;
} else {
return someObject.ToString();
}

Yours is concise as it can get.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.