Dave
Dave

Reputation: 1641

What's a good syntax in C# for "If foo isn't null, return a property of it, otherwise null"

In my little code snippet below I have a wrapper class for a simple dynamic object that, when not null, I can access two properties of, "id" and "name". It's a Facebook object, for those playing at home.

Anyway, in my GET accessor you can see I have to check if the dynamic object I was given was null, since referencing a dynamic property on a null reference will AV. But since I'm probably about the millionth person to do this, I assume there's a more concise and elegant way to express this.

Please enlighten me, oh mighty sages. Thanks!

public class IdNamePair
{
    private dynamic _data;
    public IdNamePair(dynamic data)
    {
        _data = data;
    }
    public string Id
    {
        get
        {
            return (_data == null) ? null : _data.id;
        }
    }
    public string Name
    {
        get
        {
            return (_data == null) ? null :_data.name;
        }
    }
}

Upvotes: 3

Views: 612

Answers (3)

svick
svick

Reputation: 244767

Using the code you already have is most likely the best solution. But if you wanted, you could create an extension method like this:

public static TResult Select<T, TResult>(this T obj, Func<T, TResult> func)
    where T : class
    where TResult : class
{
    return obj == null ? null : func(obj);
}

and use it like this:

public string Id
{
    get
    {
        return _data.Select(d => d.id);
    }
}

But this would make the code less readable for most people. And that method maybe should have a better name.

Doing this basically treats the nullable reference types as Maybe monad.

Upvotes: 0

Brandon Moore
Brandon Moore

Reputation: 8780

Nope, that's pretty much the way you have to do it. Guess you're smarter than you thought :)

Upvotes: 0

slugster
slugster

Reputation: 49974

There is nothing wrong with what you have done, the only thing I would do is drop the brackets and change the evaluation:

return _data != null ? _data.name : null;

Doing it that way is just (IMVHO) slightly easier to read, but fundamentally identical to what you had.

Upvotes: 6

Related Questions