I've grabbed the source code of Nullable<T> class from the https://referencesource.microsoft.com/ and put it to the file and renamed to NullableZZ (and also the sources of NonVersionableAttribute into separate file). When I've tried to build the next code:
static void Main(string[] args)
{
NullableZZ<int> n1 = 100;
NullableZZ<int> n2 = null;
}
I've got this error:
Error CS0037 Cannot convert null to 'NullableZZ' because it is a non-nullable value type ConsoleApp2 C:\Users\Roman2\source\repos\ConsoleApp2\ConsoleApp2\Program.cs
Why the C# compiler does not want to compile it? Has it some "tricks" to compile its "own" version of Nullable<T>?
Why the C# compiler does not want to compile it?
Because it doesn't have any specific knowledge of your class, but it does have specific knowledge of Nullable<T>
.
Has it some "tricks" to compile its "own" version of
Nullable<T>
?
Yes. The null
literal is convertible to Nullable<T>
for any non-nullable value type T
, and also to any reference type. It is not convertible to NullableZZ<int>
. Also, int?
is effectively shorthand for Nullable<int>
- it has special treatment.
Basically look through the specification (e.g. the ECMA C# 5 spec) and observe everywhere that it talks about Nullable<T>
. You'll find lots of places that it's mentioned.
Nullable value types have support in the framework, the language and the CLR:
Nullable<T>
type has to exist in the frameworkIf 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