" not a structure? Basically, why is C # unacceptable? I can find many good uses for this and actually can fix it by...">

Why is "struct Nullable <T>" not a structure?

Basically, why is C # unacceptable? I can find many good uses for this and actually can fix it by creating my own struct class, but why and how is its C # specification (and therefore the compiler) hindering it?

Below is an incomplete example of what I am saying.

struct MyNullable<T> where T : struct
{
    public T Value;
    public bool HasValue;

    // Need to overide equals, as well as provide static implicit/explit cast operators
}

class Program
{
    static void Main(string[] args)
    {
        // Compiles fine and works as expected
        MyNullable<Double> NullableDoubleTest;
        NullableDoubleTest.Value = 63.0;

        // Also compiles fine and works as expected
        MyNullable<MyNullable<Double>> NullableNullableTest;
        NullableNullableTest.Value.Value = 63.0;

        // Fails to compile...despite Nullable being a struct
        // Error: The type 'double?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'ConsoleApplication1.MyNullable<T>'
        MyNullable<Nullable<Double>> MyNullableSuperStruct;
    }
}
+5
source share
2 answers

That struct. It simply does not satisfy the parameter constraint of the type value type. From 10.1.5 language specification:

, , , . , , , . , , , (§4.1.10) .

, where T : struct , , .

, # ?

where T : struct T, , . Nullable<TNonNullableValueType> .

?

? . ? , T, where T : struct.

[I] , struct,

, . , Nullable<T>, , , , .

? ? , Nullable<T> , , T " ". ? , Nullable<Nullable<T>>? . , , ( , ). , int??? , , int?, , , int? ?

+8

, struct constraint, , T? . struct NULL, T?.

:

  • null ; .
  • null; , , false.
  • ??; non-nullables .
+2

All Articles