Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Generic Method handle both Reference and Nullable Value types?

Tags:

c#

.net

generics

I have a series of Extension methods to help with null-checking on IDataRecord objects, which I'm currently implementing like this:

public static int? GetNullableInt32(this IDataRecord dr, int ordinal)
{
    int? nullInt = null;
    return dr.IsDBNull(ordinal) ? nullInt : dr.GetInt32(ordinal);
}

public static int? GetNullableInt32(this IDataRecord dr, string fieldname)
{
    int ordinal = dr.GetOrdinal(fieldname);
    return dr.GetNullableInt32(ordinal);
}

and so on, for each type I need to deal with.

I'd like to reimplement these as a generic method, partly to reduce redundancy and partly to learn how to write generic methods in general.

I've written this:

public static Nullable<T> GetNullable<T>(this IDataRecord dr, int ordinal)
{
    Nullable<T> nullValue = null;
    return dr.IsDBNull(ordinal) ? nullValue : (Nullable<T>) dr.GetValue(ordinal);
}

which works as long as T is a value type, but if T is a reference type it won't.

This method would need to return either a Nullable type if T is a value type, and default(T) otherwise. How would I implement this behavior?

like image 507
Adam Lassek Avatar asked Nov 19 '08 20:11

Adam Lassek


People also ask

Can a generic type be null?

This means that you can put any object in a collection because all classes in the C# programming language extend from the object base class. Also, we cannot simply return null from a generic method like in normal method.

What is nullable reference types?

Nullable reference types are a compile time feature. That means it's possible for callers to ignore warnings, intentionally use null as an argument to a method expecting a non nullable reference. Library authors should include runtime checks against null argument values.

Why use nullable reference types c#?

Nullable reference types are a new feature in C# 8.0. They allow you to spot places where you're unintentionally dereferencing a null value (or not checking it.) You may have seen these types of checks being performed before C# 8.0 in ReSharper's Value and Nullability Analysis checks.


1 Answers

You can just declare your method like this:

public static T GetNullable<T>(this IDataRecord dr, int ordinal)
{
    return dr.IsDBNull(ordinal) ? default(T) : (T) dr.GetValue(ordinal);
}

This way, if T is a nullable int or any other nullable value type, it will in fact return null. If it's a regular datatype, it will just return the default value for that type.

like image 196
BFree Avatar answered Sep 27 '22 18:09

BFree