Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I cannot create my own analogue of Nullable<T>?

Tags:

c#

.net

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>?

like image 757
Roman Tarasiuk Avatar asked Dec 05 '22 11:12

Roman Tarasiuk


1 Answers

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:

  • The Nullable<T> type has to exist in the framework
  • The language has support as described in this answer
  • The CLR has support in terms of validating generic constraints and also boxing (where the null value of a nullable value type boxes to a null reference)
like image 178
Jon Skeet Avatar answered Dec 14 '22 22:12

Jon Skeet