Tom Pester Tom Pester - 3 months ago 10
C# Question

Nullable type as a generic parameter possible?

I want to do something like this :

myYear = record.GetValueOrNull<int?>("myYear"),


Notice the nullable type as the generic parameter.

Since the
GetValueOrNull
function could return null my first attempt was this:

public static T GetValueOrNull<T>(this DbDataRecord reader, string columnName)
where T : class
{
object columnValue = reader[columnName];

if (!(columnValue is DBNull))
{
return (T)columnValue;
}
return null;
}


But the error I'm getting now is:


The type 'int?' must be a reference type in order to use it as parameter 'T' in the generic type or method


Right!
Nullable<int>
is a
struct
! So I tried changing the class constraint to a
struct
constraint (and as a side effect can't return
null
any more):

public static T GetValueOrNull<T>(this DbDataRecord reader, string columnName)
where T : struct


Now the assignment:

myYear = record.GetValueOrNull<int?>("myYear");


Gives the following error:


The type 'int?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method


Is specifying a nullable type as a generic parameter at all possible?

Answer

Change the return type to Nullable, and call the method with the non nullable parameter

static void Main(string[] args)
{
    int? i = GetValueOrNull<int>(null, string.Empty);
}


public static Nullable<T> GetValueOrNull<T>(DbDataRecord reader, string columnName) where T : struct
{
    object columnValue = reader[columnName];

    if (!(columnValue is DBNull))
    	return (T)columnValue;

    return null;
}