简体   繁体   中英

Syntactic sugar for “If this parameter is null, automatically return null”

Is there any case for syntactic sugar that returns null when a specific parameter is null? Does this exist?

public DataObj GetMyData(DataSource source?null, User currentUser?null, string path) {
    // Code starts here. source and currentUser are not null.
}

or this

public DataObj GetMyData(DataSource source!, User currentUser!, string path) {
    // Code starts here. source and currentUser are not null.
}

So the above would return null if either the source or currentUser were null without having to execute the method, but it would execute if only the path was null.

public DataObj GetMyData(DataSource source, User currentUser, string path) {
    if (source == null || currentUser == null)
    { 
        return null;
    }
    // The rest of your code here
}

You could also use ArgumentNullExceptions, but then you are creating additional exception handling work elsewhere especially if null parameters are ok, but you don't get a value from it.

C# 6 is proposing a null propagation operator ? that will turn:

double? minPrice = null;
if (product != null
    && product.PriceBreaks != null
    && product.PriceBreaks[0] != null)
{
  minPrice = product.PriceBreaks[0].Price;
}

into:

var minPrice = product?.PriceBreaks?[0]?.Price;

No, there is no syntactic sugar to return null.

I think the closest thing that exist is operations on nullable values:

int? Add(int? l, int? r)
{
    return l + r;  
}

Will give you "HasValue = false" if either operand does not have value.

You may also want to read about "Maybe monad" which is very close to what you are looking for - ie Marvels of Monads tries to explain one in C# (nullable values is example on one, but apply only to value types).

If it is something you find yourself doing a few times, it would make sense to put it into a generic method. That method can do the checks and it will use a function that will do the actual operation after checking for the nulls on the arguments.

public T OperateIfNotNull<T, V1, V2>(V1 arg1, V2 arg2, string path, Func<V1, V2, string, T> operation) where T : class
{
    if ((arg1 == null) || (arg2 == null) || string.IsNullOrWhiteSpace(path))
        return null;

    return operation(arg1, arg2, path);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM