1
    public sealed class MyClass<T>
    {
        private T? myField;
    }

This code compiles fine, yet when I use it with reference type (like T=string) I will get nullable myField (as expected). But when I use value type (like int) I will get non-nullable myField which I didn't expect, especially considering lack of error.

Is it possible to write universal type holding nullable value or reference?

greenoldman
  • 16,895
  • 26
  • 119
  • 185
  • What version of C# are you using? – Dai Dec 10 '22 at 16:59
  • One workaround is to define separate generic extension methods with different `where` constraints. – Dai Dec 10 '22 at 16:59
  • @Dai, net 7.0 with C#11 (but I noticed this behavior with net 6.0 as well). Constraints do not allow overloads, extensions are for methods as you pointed out, I have to store the data. – greenoldman Dec 10 '22 at 17:07

1 Answers1

1

The T? meaning for reference types and value types is completely different. For value type it is really just a syntactic sugar for Nullable<T>, while for reference type it is merely an ignorable tip. If you want to have MyClass wrapping a nullable int then use it with int? type: MyClass<int?>.

You could constraint the T with where T : struct - then the T? will really mean Nullable<T> and you'll get myField equal to null initially when using MyClass<int>, but you will no longer be able to use e.g. MyClass<string>.

As far as I know you can't mix both behaviours and let the runtime choose one depending on the generic T type.

Maku
  • 1,464
  • 11
  • 20