Reputation: 2425
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.
Upvotes: 0
Views: 2722
Reputation: 31616
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);
}
Upvotes: 0
Reputation: 21712
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;
Upvotes: 3
Reputation: 100547
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 - i.e. Marvels of Monads tries to explain one in C# (nullable values is example on one, but apply only to value types).
Upvotes: 0