Search code examples
c#.netnullable

Nullable<int?> is not possible, Why not?


Excuse me if its a silly question, I am trying to get a better understanding of Nullable types in .Net.

From what i notice from Microsoft source code (using ReSharper), I understand that Nullable is a struct and T needs to be a struct

public struct Nullable<T> where T : struct

Now, I tried to do something like this

public struct CustomNullable<T> where T : struct
{
}
public class CustomNullableClass<T> where T : struct
{
}

And I get an error when I compile:

  Nullable<int?> a = null;
  Nullable<Nullable<int>> a1 = null;

For the above mentioned code I get an error 'Only non-nullable value types could be underlying of System.Nullable', but how is this enforced in the Nullable type ?

And for

   CustomNullable<int?> a2 = null;
   CustomNullableClass<int?> a3 = null;

I get an error 'The type System.Nullable must be non-nullable value type in order to use it as parameter T '.

I am bit confused now, can some one help me understand whats going on or have I not understood something ?

Thanks a lot in advance.

EDIT: If structs are value types and value types can't be null, how can a Nullable be a struct?

Credit : spender


Solution

  • Actually, it's an internal hack somewhere in the C# compiler (guessing). You cannot replicate it in your own classes. If you make your own type, using the exact same IL, it will not enforce that additional hidden constraint.