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'
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.
" " 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.
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.
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.
You can, but you have to add another constraint: the struct
constraint.
public static void DoSomething<T>(T? defaultValue) where T : struct, Enum
{
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With