C# Extension method, GetValueOrNull for value type object

Return null if the value type object has default value.

  1. public static T? GetValueOrNull<t>( this T value ) where T : struct
  2. {
  3. if( value.Equals( default( T ) ) )
  4. return new Nullable<t>();
  5. else
  6. return value;
  7. }
  8.  
  9. // Usage
  10. int i = default(int); //0
  11. int? i = i.GetValueOrNull();
  12. Console.Writeline( i.HasValue );

The output is false

( Maybe there is something else doing the same thing. ?! )