title: How do I tell the compiler about my nullable c# generic constraints?
body: <p>I've got an editor that lets the user edit the &quot;simple&quot; properties of objects (int, string, DateTime, etc.), so it iterates through the properties and then constructs for each simple property an object to support the editing:</p>
  <pre><code>#nullable enable
  
  public class DataNode&lt;T&gt;
  {
     protected PropertyInfo Prop;
     protected object Source;
     protected T Value;
     protected bool Modified;
  
     public DataNode(PropertyInfo prop, object source)
     {
        Prop = prop;
        Source = source;
        object? value = prop.GetValue(source);
        if (value is T t)
           Value = t;
        else
           Value = default;
        Modified = false;
     }
  
     public virtual bool IsValid()
     {
        return true;
     }
  
     public void Save()
     {
        if (Modified)
        {
           Prop.SetValue(Source, Value);
           Modified = false;
        }
     }
  }
  </code></pre>
  <p>I then have subclasses for specific properties - for example, if there's an int property where I don't want the user to be able to enter a negative value, I can create a specific subclass:</p>
  <pre><code>public class NonNegativeIntNode : DataNode&lt;int&gt;
  {
     public NonNegativeIntNode (PropertyInfo prop, object source)
     : base(prop, source)
     {
     }
  
     public override bool IsValid()
     {
        return Value &gt;= 0;
     }
  }
  </code></pre>
  <p>So that all works fine, and before you ask:</p>
  <ol>
  <li>The selection of which DataNode class to use is controlled by custom attributes on the properties</li>
  <li>The DataNode does more than this that I've left out for simplicity.  For example the BoolDataNode class knows that to edit this value it should use a checkbox</li>
  </ol>
  <p>The problem is that the compiler is grumbling that &quot;Value = default;&quot; is a possible null reference assignment, and that the DataNode constructor might be exiting with a null value for 'Value'.</p>
  <p>I can keep the compiler happy by defining Value as &quot;protected T? Value&quot; but that adds unnecessary complication elsewhere to check for a null value when I know darn well that inside BoolDataNode that Value will never be null.</p>
  <p>I tried splitting DataNode into two classes - NullableDataNode and NonNullableDataNode - but inside NonNullableDataNode, even though I specify &quot;where T: notnull&quot;, the compiler is still worried about 'default'</p>
  <p>It seems like saying &quot;where T: notnull&quot; means &quot;I am never going to set Value to null&quot; where what I want to tell the compiler is &quot;T is a type that cannot be null&quot; (like bool)</p>
  <p>Is there a way to reassure the compiler that all is well, without simply turning off all the nullability warnings with pragmas?</p>