I have read about notnull
constraint in C# and it was written that "This allows either value types or non-nullable reference types but not nullable reference types."
(the quote is from "Programming C# - 10.0 By Ian Griffiths)
I tried checking this constraint in the code below:
MyTestClass<int?> instance1 = new MyTestClass<int?>();
MyTestClass<string?> instance2 = new MyTestClass<string?>();
public class MyTestClass<T> where T : notnull
{
T Value { get; set; }
public MyTestClass()
{
Value = default(T);
if (Value == null)
Console.WriteLine($"Type of T is {typeof(T)} and its default value is 'Null'");
else
Console.WriteLine($"Type of T is {typeof(T)} and its default value is {Value}");
}
}
as you can see I instantiated my generic class with nullable types int?
(nullable value type) and string?
(nullable reference type) and it still works for me.
It also prints the output like this for me:
Type of T is System.Nullable`1[System.Int32] and its default value is 'Null'
Type of T is System.String and its default value is 'Null'
Type of T is System.Int32 and its default value is 0
Type of T is System.String and its default value is 'Null'"
It behaves 'string?' as 'string' and detects both as non-nullable. what can be the reason for these to happen?