Cleaner way to do a null check in C#? [duplicate]

2019-01-12 13:06发布

This question already has an answer here:

Suppose, I have this interface,

interface IContact
{
    IAddress address { get; set; }
}

interface IAddress
{
    string city { get; set; }
}

class Person : IPerson
{
    public IContact contact { get; set; }
}

class test
{
    private test()
    {
        var person = new Person();
        if (person.contact.address.city != null)
        {
            //this will never work if contact is itself null?
        }
    }
}

Person.Contact.Address.City != null (This works to check if City is null or not.)

However, this check fails if Address or Contact or Person itself is null.

Currently, one solution I could think of was this:

if (Person != null && Person.Contact!=null && Person.Contact.Address!= null && Person.Contact.Address.City != null)

{ 
    // Do some stuff here..
}

Is there a cleaner way of doing this?

I really don't like the null check being done as (something == null). Instead, is there another nice way to do something like the something.IsNull() method?

19条回答
我命由我不由天
2楼-- · 2019-01-12 13:52

I have an extension that could be useful for this; ValueOrDefault(). It accepts a lambda statement and evaluates it, returning either the evaluated value or a default value if any expected exceptions (NRE or IOE) are thrown.

    /// <summary>
    /// Provides a null-safe member accessor that will return either the result of the lambda or the specified default value.
    /// </summary>
    /// <typeparam name="TIn">The type of the in.</typeparam>
    /// <typeparam name="TOut">The type of the out.</typeparam>
    /// <param name="input">The input.</param>
    /// <param name="projection">A lambda specifying the value to produce.</param>
    /// <param name="defaultValue">The default value to use if the projection or any parent is null.</param>
    /// <returns>the result of the lambda, or the specified default value if any reference in the lambda is null.</returns>
    public static TOut ValueOrDefault<TIn, TOut>(this TIn input, Func<TIn, TOut> projection, TOut defaultValue)
    {
        try
        {
            var result = projection(input);
            if (result == null) result = defaultValue;
            return result;
        }
        catch (NullReferenceException) //most reference types throw this on a null instance
        {
            return defaultValue;
        }
        catch (InvalidOperationException) //Nullable<T> throws this when accessing Value
        {
            return defaultValue;
        }
    }

    /// <summary>
    /// Provides a null-safe member accessor that will return either the result of the lambda or the default value for the type.
    /// </summary>
    /// <typeparam name="TIn">The type of the in.</typeparam>
    /// <typeparam name="TOut">The type of the out.</typeparam>
    /// <param name="input">The input.</param>
    /// <param name="projection">A lambda specifying the value to produce.</param>
    /// <returns>the result of the lambda, or default(TOut) if any reference in the lambda is null.</returns>
    public static TOut ValueOrDefault<TIn, TOut>(this TIn input, Func<TIn, TOut> projection)
    {
        return input.ValueOrDefault(projection, default(TOut));
    }

The overload not taking a specific default value will return null for any reference type. This should work in your scenario:

class test
{
    private test()
    {
        var person = new Person();
        if (person.ValueOrDefault(p=>p.contact.address.city) != null)
        {
            //the above will return null without exception if any member in the chain is null
        }
    }
}
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-01-12 13:52

As much as I love C#, this is one thing that's kind of likable about C++ when working directly with object instances; some declarations simply cannot be null, so there's no need to check for null.

The best way you can get a slice of this pie in C# (which might be a bit too much redesigning on your part - in which case, take your pick of the other answers) is with struct's. While you could find yourself in a situation where a struct has uninstantiated "default" values (ie, 0, 0.0, null string) there's never a need to check "if (myStruct == null)".

I wouldn't switch over to them without understanding their use, of course. They tend to be used for value types, and not really for large blocks of data - anytime you assign a struct from one variable to another, you tend to be actually copying the data across, essentially creating a copy of each of the original's values (you can avoid this with the ref keyword - again, read up on it rather than just using it). Still, it may fit for things like StreetAddress - I certainly wouldn't lazily use it on anything I didn't want to null-check.

查看更多
成全新的幸福
4楼-- · 2019-01-12 14:02

Update 28/04/2014: Null propagation is planned for C# vNext


There are bigger problems than propagating null checks. Aim for readable code that can be understood by another developer, and although it's wordy - your example is fine.

If it is a check that is done frequently, consider encapsulating it inside the Person class as a property or method call.


That said, gratuitous Func and generics!

I would never do this, but here is another alternative:

class NullHelper
{
    public static bool ChainNotNull<TFirst, TSecond, TThird, TFourth>(TFirst item1, Func<TFirst, TSecond> getItem2, Func<TSecond, TThird> getItem3, Func<TThird, TFourth> getItem4)
    {
        if (item1 == null)
            return false;

        var item2 = getItem2(item1);

        if (item2 == null)
            return false;

        var item3 = getItem3(item2);

        if (item3 == null)
            return false;

        var item4 = getItem4(item3);

        if (item4 == null)
            return false;

        return true;
    }
}

Called:

    static void Main(string[] args)
    {
        Person person = new Person { Address = new Address { PostCode = new Postcode { Value = "" } } };

        if (NullHelper.ChainNotNull(person, p => p.Address, a => a.PostCode, p => p.Value))
        {
            Console.WriteLine("Not null");
        }
        else
        {
            Console.WriteLine("null");
        }

        Console.ReadLine();
    }
查看更多
别忘想泡老子
5楼-- · 2019-01-12 14:02

If for some reason you don't mind going with one of the more 'over the top' solutions, you might want to check out the solution described in my blog post. It uses the expression tree to find out whether the value is null before evaluating the expression. But to keep performance acceptable, it creates and caches IL code.

The solution allows you do write this:

string city = person.NullSafeGet(n => n.Contact.Address.City);
查看更多
Juvenile、少年°
6楼-- · 2019-01-12 14:03

In a generic way, you may use an expression tree and check with an extension method:

if (!person.IsNull(p => p.contact.address.city))
{
    //Nothing is null
}

Full code:

public class IsNullVisitor : ExpressionVisitor
{
    public bool IsNull { get; private set; }
    public object CurrentObject { get; set; }

    protected override Expression VisitMember(MemberExpression node)
    {
        base.VisitMember(node);
        if (CheckNull())
        {
            return node;
        }

        var member = (PropertyInfo)node.Member;
        CurrentObject = member.GetValue(CurrentObject,null);
        CheckNull();
        return node;
    }

    private bool CheckNull()
    {
        if (CurrentObject == null)
        {
            IsNull = true;
        }
        return IsNull;
    }
}

public static class Helper
{
    public static bool IsNull<T>(this T root,Expression<Func<T, object>> getter)
    {
        var visitor = new IsNullVisitor();
        visitor.CurrentObject = root;
        visitor.Visit(getter);
        return visitor.IsNull;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Person nullPerson = null;
        var isNull_0 = nullPerson.IsNull(p => p.contact.address.city);
        var isNull_1 = new Person().IsNull(p => p.contact.address.city);
        var isNull_2 = new Person { contact = new Contact() }.IsNull(p => p.contact.address.city);
        var isNull_3 =  new Person { contact = new Contact { address = new Address() } }.IsNull(p => p.contact.address.city);
        var notnull = new Person { contact = new Contact { address = new Address { city = "LONDON" } } }.IsNull(p => p.contact.address.city);
    }
}
查看更多
戒情不戒烟
7楼-- · 2019-01-12 14:04

in your case you could create a property for person

public bool HasCity
{
   get 
   { 
     return (this.Contact!=null && this.Contact.Address!= null && this.Contact.Address.City != null); 
   }     
}

but you still have to check if person is null

if (person != null && person.HasCity)
{

}

to your other question, for strings you can also check if null or empty this way:

string s = string.Empty;
if (!string.IsNullOrEmpty(s))
{
   // string is not null and not empty
}
if (!string.IsNullOrWhiteSpace(s))
{
   // string is not null, not empty and not contains only white spaces
}
查看更多
登录 后发表回答