Thursday, May 5, 2011

nullable types to object

Using dotnet 2.0. Can the following code be improved in style ?

 private object GetObj_Version1(int? num)
 {
  return num ?? (object)DBNull.Value;
 }

The cast looks a bit messy to me. Version2 below avoids the cast, but its long winded :

    private object GetObj_Version2(int? num)
 {
  object numObj;
  if (num.HasValue)
   numObj = num.Value;
  else
   numObj = DBNull.Value;

  return numObj;
 }

Can you think of an alternative which is both short and avoids the cast ? TIA.

From stackoverflow
  • If you want to insert values to the database, then you can directly pass the nullable type as a procedure's parameter.

    param.Add("@Param1", nullableParam);
    
    Marc Gravell : Not quite; if the nullableParam doesn't have a value, then it will be boxed to `null` - and a parameter with a `null` value is not sent. So if there is a non-null default to a SP etc, then this does something different. Of course, you could use this and then "fix up" the parameter values before executing the command.
  • The cast, in this case, does nothing at runtime - it is there purely for the compiler. If you really hate it, perhaps:

        static readonly object NullObject = DBNull.Value;
        private object GetObj_Version1(int? num)
        {
            return num ?? NullObject;
        }
    

    But I'd leave it myself. As an aside - since you are going to box it anyway, you could dispense with the overload, and just work with object - then you don't even need the static field:

        private object GetObj_Version1(object value)
        {
            return value ?? DBNull.Value;
        }
    
    Moe Sisko : Thanks. Looks like I'll stick with the cast, especially since there's no runtime penalty in this case.

0 comments:

Post a Comment