Search code examples
c#.netgenericsnullable

Return a generic nullable Element


I'm trying to make a method that returns the highest value of an Array with generic elements that can be Nullable.

 public T Greatest<T>(T?[] array) where T : struct, IComparable<T> 
 {
     T? Greater = null;
     foreach (var elem in array)
     {
         if(elem.HasValue)
         {
             if(Greater.HasValue)
             {
                 if(Greater.Value.CompareTo(elem.Value) < 0)
                 {
                     Greater = elem;
                 }
             }
             else
             {
                 Greater = elem;
             }
        }
    }

    //Problem here: What is the best way to return the greatest value?
    // ****
    return Greater.Value; // Possible InvalidOperationException 
    // ****
}

What is the proper way to return the value?


Solution

  • Nullable.GetValueOrDefault