title: Returning nullable and null in single C# generic method?
body: <p>Is it possible in a C# generic method to return either an object type or a Nullable type?</p>
  
  <p>For instance, if I have a safe index accessor for a <code>List</code> and I want to return a value that I can check later with either <code>== null</code> or <code>.HasValue()</code>.</p>
  
  <p>I currently have the following two methods:</p>
  
  <pre><code>static T? SafeGet&lt;T&gt;(List&lt;T&gt; list, int index) where T : struct 
  {
      if (list == null || index &lt; 0 || index &gt;= list.Count)
      {
          return null;
      }
  
      return list[index];
  }
  
  static T SafeGetObj&lt;T&gt;(List&lt;T&gt; list, int index) where T : class
  {
      if (list == null || index &lt; 0 || index &gt;= list.Count)
      {
          return null;
      }
  
      return list[index];
  }
  </code></pre>
  
  <p>If I try to combine the methods into a single method.</p>
  
  <pre><code>static T SafeGetTest&lt;T&gt;(List&lt;T&gt; list, int index)
  {
      if (list == null || index &lt; 0 || index &gt;= list.Count)
      {
          return null;
      }
  
      return list[index];
  }
  </code></pre>
  
  <p>I get a compile error:</p>
  
  <blockquote>
    <p>Cannot convert null to type parameter 'T' because it could be a non-nullable value type. Consider using 'default(T)' instead.</p>
  </blockquote>
  
  <p>But I don't want to use <code>default(T)</code> because in the case of primitives, <code>0</code>, which is the default for an <code>int</code>, is a possible real value that I need to distinguish from a not available value. </p>
  
  <p>Is it possible for these methods be combined into a single method?</p>
  
  <p>(For the record I am using .NET 3.0 and while I interested in what more modern C# can do I will personally only be able to use answers that work in 3.0)</p>