Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# null-conditional shorthand for method arguments

The null-conditional operator is very useful when the method belongs to the object in question, but what if the object in question is an argument? For example, can this be shortened?

var someList = new List<SomeType>();
if (anotherList.Find(somePredicate) != null)
{
    someList.Add(anotherList.Find(somePredicate))
}

One solution I thought of was to use an extension method like below:

public static void AddTo<T>(this T item, List<T> list)
{
    list.Add(item);
}

With that the first code block can be reduced to:

var someList = new List<SomeType>();
anotherList.Find(somePredicate)?.AddTo(someList);

But this solution is specific to this example (i.e. adding an object to a list if it's not null). Is there a general way to indicate that if a parameter is null, the method should not be run?

like image 344
Zachary Avatar asked Dec 23 '22 08:12

Zachary


1 Answers

Never do this

var someList = new List<SomeType>();
if (anotherList.Find(somePredicate) != null)
{
    someList.Add(anotherList.Find(somePredicate))
}

this will search the list twice which is unnecessary. use a temporary variable instead.

var someList = new List<SomeType>();
var find = anotherList.Find(somePredicate);
if (find != null) someList.Add(find);

Is there a general way to indicate that if a parameter is null, the method should not be run?

Currently there is no such feature. how ever there are other alternatives that work better like in other answers provided.

like image 166
M.kazem Akhgary Avatar answered Jan 14 '23 01:01

M.kazem Akhgary