1
Nullable<int> intNullable = null;//this is ok since `Nullable<T> where T : struct`

However Nullable<Nullable<int>> is NOT OK although Nullable<int> is a struct.

How is this possible?

Seckin Celik
  • 142
  • 2
  • 11
  • public struct Nullable where T : struct – Seckin Celik Jan 03 '19 at 18:49
  • 1
    Rather than abstract corners of the language... What **problem** led to you wanting a `Nullable>`? Give us that to solve instead. – Damien_The_Unbeliever Jan 03 '19 at 18:50
  • 2
    Bear in mind that the compilers have specific support for nullables. Whilst the type system may say something is okay, it's fine for the compilers to get upset with it. – Damien_The_Unbeliever Jan 03 '19 at 18:52
  • @Damien_The_Unbeliever, I did not encounter any specific problem besides not being able to place a struct where a struct is required. – Seckin Celik Jan 03 '19 at 18:55
  • @SeckinCelik A *non-nullable* struct is required, as per the error message you get when you try to do it. You're providing a *nullable* struct, which doesn't meet that condition. – Servy Jan 03 '19 at 18:56
  • @SeckinCelik - you've misunderstood. I fully understand you tried to create a `Nullable>`. I wanted to understand what *led you to wanting to create such a thing in the first place*. – Damien_The_Unbeliever Jan 03 '19 at 19:20

1 Answers1

3

There is special language support for Nullable<T>, in numerous ways, one of which is that Nullable<Nullable<T>> is not valid. You could not create your own custom generic struct that could have any other struct except itself as the generic argument. The generic constraint function of C# just isn't powerful enough to do it.

Also note that the error message does not say that Nullable<int> isn't a struct, it says that it must be a non-nullable struct. Nullable<int> isn't a non-nullable struct. It's a nullable struct.

Servy
  • 197,813
  • 25
  • 319
  • 428