Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# 7.3 Enum constraint: Why can't I use the nullable enum?

Now that we have enum constraint, why doesn't compiler allow me to write this code?

public static TResult? ToEnum<TResult>(this String value, TResult? defaultValue)
    where TResult : Enum
{
    return String.IsNullOrEmpty(value) ? defaultValue : (TResult?)Enum.Parse(typeof(TResult), value);
}

The compiler says:

Error CS0453 The type 'TResult' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable'

like image 624
Kirill Kovalenko Avatar asked May 15 '18 13:05

Kirill Kovalenko


People also ask

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What do you mean by C?

" " C is a computer programming language. That means that you can use C to create lists of instructions for a computer to follow. C is one of thousands of programming languages currently in use.

What language is C written in?

It was based on CPL (Combined Programming Language), which had been first condensed into the B programming language—a stripped-down computer programming language—created in 1969–70 by Ken Thompson, an American computer scientist and a colleague of Ritchie.

Is C language hard to learn?

C is more difficult to learn than JavaScript, but it's a valuable skill to have because most programming languages are actually implemented in C. This is because C is a “machine-level” language. So learning it will teach you how a computer works and will actually make learning new languages in the future easier.


2 Answers

You can, but you have to add another constraint: the struct constraint.

public static void DoSomething<T>(T? defaultValue) where T : struct, Enum
{
}
like image 59
Patrick Hofman Avatar answered Sep 26 '22 01:09

Patrick Hofman


Because System.Enum is a class, you cannot declare a variable of type Nullable<Enum> (since Nullable<T> is only possible if T is a struct).

Thus:

Enum? bob = null;

won't compile, and neither will your code.

This is definitely strange (since Enum itself is a class, but a specific Enum that you define in your code is a struct) if you haven't run into it before, but it is clearly a class (not a struct) as per the docs and the source code.

like image 23
mjwills Avatar answered Sep 28 '22 01:09

mjwills