Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly deal with System.Nullable<T> fields of LinqToSql classes?

Tags:

c#

.net

nullable

I've got a table with some nullable double fields. Working with LinqToSQL trying to use the field directly I get

Argument type System.Nullable is not assignable to parameter type double

How do I deal with this correctly?

like image 421
Ivan Avatar asked Jun 03 '11 22:06

Ivan


2 Answers

The problem has nothing to do with Linq. It's got to do with conversion between double and double?/Nullable<double>.

Implicit conversion from double? to double is not allowed:

double? foo ;
double  bar = foo ;
  • You can reference the double value directly:

      double? foo ;
      double  bar = foo.Value ;
    

    This will throw a NullReferenceException if the Nullable<T> is null (that is, .HasValue is false).

  • You can cast it:

      double? foo ;
      double  bar = (double) foo ;
    

    Again, you'll get an exception if the Nullabl<T> is null.

  • You can use the null coalescing operator to assign a default value if the Nullable<T> is null:

      double? foo ;
      double  bar = foo ?? -1.0 ;
    

    This, natch, avoids the NullReferenceException` problem.

  • You can use the ternary operator in the same vein as the null coalescing operator:

      double? foo ;
      double  bar = ( foo.HasValue ? foo.Value : -2 ) ;
    
  • Finally, you can use regular conditional logic to follow an alternative path:

      double? foo ;
      double  bar ;
    
      if ( foo.HasValue )
      {
        doSomething(foo.Value) ;
      }
      else
      {
        doSomething() ;
      }
    

Those are about the options. Which is correct? I don't know. It depends on your context.

like image 152
Nicholas Carey Avatar answered Sep 28 '22 06:09

Nicholas Carey


You can use

double value = theObject.TheProperty.GetValueOrDefault();

When you have a Nullable<T> and you need a value of type T. This will normalize any null to the default value of T, which will be 0.0 for a double. If you want something other than the default, you can work around it another way.

double value = theObject.TheProperty ?? 1d; // where 1 replaces any null
like image 44
Anthony Pegram Avatar answered Sep 28 '22 04:09

Anthony Pegram