How to add a constraint of Nullable Types to a generics method

J

Joe Bloggs

Hi,

compiling the following code:


public class App
{
static void Main()
{
int? x = 5;
bool? i = null;
Console.WriteLine(GetType(x).FullName);
Console.WriteLine(" x={0}", GetSafeValue(x));
Console.WriteLine(" i={0}", GetSafeValue(i));
Console.ReadLine();
}


public static object GetSafeValue<T, N>(T value) where T:struct
{


if (!IsNullableValueType(GetType(value)))
{
Console.WriteLine(" {0} is not a Nullable type",
value.GetType());
return value;
}
object nullableValue = value;


return nullableValue ??
GetDefaultDataTypeValue((GetType(value)).GetGenericArguments()[0]);


}



}


I get the error message
"The type 'int?' must be a non-nullable value type in order to use it
as parameter 'T' in the generic type or method
'App.GetSafeValue<T>(T)'"

Obviously, I have set the constraint to only accept value types.


Now, how do I modify the constraint so that I can accept either value
types or Nullable types?


Thanks in advance.
 
J

Joanna Carter [TeamB]

"Joe Bloggs" <[email protected]> a écrit dans le message de [email protected]...

| Now, how do I modify the constraint so that I can accept either value
| types or Nullable types?

I'm not sure what you are trying to achieve here but have you tried the
following code ?

public static object GetSafeValue<T>(Nullable<T> value) where T : struct
{
return value.GetValueOrDefault(default(T));
}

static void Main(string[] args)
{
int? x = 5;
bool? i = null;
Console.WriteLine(x.GetType().FullName);
Console.WriteLine(" x={0}", GetSafeValue(x));
Console.WriteLine(" i={0}", GetSafeValue(i));
Console.ReadLine();
}

Joanna
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top