Why cannot concatenate the code to simply it?

Jon Tavakoli 1 Reputation point
2022-10-18T13:38:23.95+00:00

Why cannot I simplify the following code to a single line.

The way the code has to be written in order for the Compiler to build is as follow:

var headers = this.GetHeaders<THeader>(name);
return headers == null ? default : headers.FirstOrDefault();

But if I try to combine them into a single line of code as follow it throws compile time error.

return this.GetHeaders<THeader>(name)?.FirstOrDefault() ?? default;

Any thoughts on why?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,482 questions
Not Monitored
Not Monitored
Tag not monitored by Microsoft.
36,984 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Michael Taylor 49,871 Reputation points
    2022-10-18T14:46:21.9+00:00

    You can combine them.

       return GetHeaders<THeader>(name)?.FirstOrDefault() ?? default;  
    

    But note that this is changing the expression ever so slightly. This expression says to call the GetHeaders method and if it doesn't return null then get the first item. Then if the first item is not null return it otherwise return default(T).

    In your original code you are calling GetHeaders. If the value is not null then you get the first item and return it (whether it is null or not). However if GetHeaders returns null then you return default(T). Note that I assume that method is returning IEnumerable<T> and therefore should never return null. In pretty much every implementation (including if you're using the iterator syntax) it will return an empty enumerable and never null.

    If you're getting an error on the above expression I gave then please tell us what the actual error is.

    0 comments No comments