Zachary
Zachary

Reputation: 326

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?

Upvotes: 5

Views: 536

Answers (3)

M.kazem Akhgary
M.kazem Akhgary

Reputation: 19149

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.

Upvotes: 4

Namoshek
Namoshek

Reputation: 6544

You could also use just:

var someList = new List<SomeType>();
someList.AddRange(anotherList.Where(somePredicate));

In your case you probably need to make sure that your predicate only finds at max one element.

Upvotes: 4

rokkerboci
rokkerboci

Reputation: 1167

TLDR: Not yet.

The team plans to implement a functionality into the language, that would do this exact thing. It would look something like this:

someList.Add(anotherList.Find(somePredicate) ?? return);

In which the ?? return checks whether the first argument is null, and if it is, than it returns. (Or you could write break if that is what you want)

I am not sure if this is a thing they are working on at the moment, and if it will be included in the next version of C#, but would go a long way if it is going to be.

Upvotes: 2

Related Questions