views:

136

answers:

3

I alredy have this:

public static object GetDBValue(object ObjectEvaluated)
 {
  if (ObjectEvaluated == null)
   return DBNull.Value;
  else
   return ObjectEvaluated;
 }
used like:

 List<SqlParameter> Params = new List<SqlParameter>();
 Params.Add(new SqlParameter("@EntityType", GetDBValue(EntityType)));

Now i wanted to keep the same interface but extend that to use it with nullable

 public static object GetDBValue(int? ObjectEvaluated)
 {
  if (ObjectEvaluated.HasValue)
   return ObjectEvaluated.Value;
  else
   return DBNull.Value;
 }

 public static object GetDBValue(DateTime? ObjectEvaluated)
 {...}

but i want only 1 function GetDBValue for nullables. How do I do that and keep the call as is is? Is that possible at all?

I can make it work like:

 public static object GetDBValue<T>(Nullable<T> ObjectEvaluated) where T : struct
 {
  if (ObjectEvaluated.HasValue)
   return ObjectEvaluated.Value;
  else
   return DBNull.Value;
 }

But the call changes to:

Params.Add(new SqlParameter("@EntityID ", GetDBValue<int>(EntityID)));
+3  A: 

The generic version that you have is fine, although you can shorten it even more with the null-coalescing operator:

public static object GetDBValue<T>(Nullable<T> ObjectEvaluated)
    where T : struct
{
    return ObjectEvaluated ?? (object)DBNull.Value;
}

What you might be missing is that you don't need to use the generic parameter when you call it; C#'s type inference will figure it out for you:

int? x = null;
object y = GetDBValue(x);
Aaronaught
The problem is the calling for that would not be GetDBValue(x) but GetDBValue<int>(x)!!! and that is the reason of my question that i don't want to have n versions of the function to keep the same calling, and i think that is not possible at all but maybe someone...
@ferch: No, that's not correct. C# does type inference on generics. The code will compile without the `<int>` in the method call. It will work exactly as written in this answer.
Aaronaught
Sorry Aaronaught, you are correct. I did something wrong the first time i tried and got a compilation error. It works as charm.I dont shorten the if because i still need the value when not null and not the nullable.Thanks
+1  A: 

If EntityID (in your last example) is a Nullable type then the compiler will know to call GetDBValue without specifying the underlying type.

Adam Ruth
+1  A: 

I'm not sure there is much point doing that; what you have already boxes (since it returns object), you might as well let the CLR do that for you. Simply:

public static object GetDBValue(object ObjectEvaluated)
{
  return ObjectEvaluated ?? DBNull.Value;
}

There isn't much benefit adding generics here (since we don't use the T).

You certainly could add a generic method, but what does it add?

Marc Gravell