Why doesn't default work with double brackets?

Why is this compiling:

return default(T);

but this is not so:

return default((T));

Full method

public static T PenultimateOrDefault<T>(this IEnumerable<T> items)
{
    if (items.Count() >= 2)
        return items.ElementAt(items.Count() - 2);
    else
        return default(T);
}

Errors for default((T)):

; expected
Invalid expression term ')'
Type expected

So, it looks like the parser is recognized by double brackets.

+3
source share
3 answers

Well, that’s just not how the language is indicated.

It is important to understand what defaultis like typeof- these are operators 1 and not method calls. It is not like the type name is an argument - it is an operand, and it is assumed that the operand will be just a type name.

Section 7.6.13 of the C # 5 specification shows the construction of a default expression:

default value expression:
  default (type)

type - . , , :

(string) x = ""; // Invalid
var x = new List<(string)>(); // Invalid

1 " " ; " ", , .

+9

, , (AnyType) ( (T)) , .

+7

:

return default(T);

.

:

return default((T));

.

0

All Articles