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

  • Thread starter Thread starter Joe Bloggs
  • Start date Start date
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.
 
Joe,

Why not just get the Value on the nullable to begin with? It will
return a default value if it is "null" (meaning, it is flagged as null, it
isn't actually null).

Hope this helps.
 
Joe Bloggs said:
public static object GetSafeValue<T, N>(T value) where T:struct

Yes, struct excludes nullable types.
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?

You can't do it statically. You'll have to do it at runtime.

-- Barry
 

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

Back
Top