user331940
user331940

Reputation: 23

Nullable<T> as a parameter

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)));

Upvotes: 2

Views: 3422

Answers (3)

Marc Gravell
Marc Gravell

Reputation: 1063864

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?

Upvotes: 1

Adam Ruth
Adam Ruth

Reputation: 3655

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

Upvotes: 1

Aaronaught
Aaronaught

Reputation: 122664

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);

Upvotes: 5

Related Questions