Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why generic method that accept reference types doesn't accept nullable-types as arguments?

At a glance,

public static class Conversion
{
    public static T Read<T>(object value) where T :class
    {
        if (value is DBNull) return null;
        if (value is null) return null;

        if (value is Enum) return (T)Enum.Parse(typeof(T), value.ToString(), true);
        return (T)Convert.ChangeType(value, typeof(T));
    }
}

When calling a Read<T> function

var myVariable = Conversion.Read<bool?>(Row[nameof(IsFetchNextRecordAfterDelete)]);

Error CS0452 The type 'bool?' must be a reference type in order to use it as parameter 'T' in the generic type or method 'Conversion.Read(object)'

Wonder why? the bool? is nullable that's mean its a reference type, and generic method declared where T : class

like image 250
deveton Avatar asked Jan 26 '23 14:01

deveton


2 Answers

'bool?' is not a reference type. It is a nullable value type. see Nullable value types (C# reference) The underlying type is a struct (which is a value type).

like image 81
Johan Donne Avatar answered Jan 28 '23 04:01

Johan Donne


where T :class

This constraint means that the type argument that you will provide will be a reference type that includes any class,interface, delegate, or array type. Type Constraints

Nullable-types come under the category of value types not as reference.

like image 20
pluto20010 Avatar answered Jan 28 '23 04:01

pluto20010