Search code examples
c#genericstype-conversionnullable

A value of type '<null>' cannot be used as a default parameter because there are no standard conversions to type 'T'


I am getting the Error:

A value of type '' cannot be used as a default parameter because there are no standard conversions to type 'T'

while trying to write this piece of code

protected T GetValue<T>(Expression<Func<T>> property, T defaultValueIfNull = null);

Does anybody has idea that how to make null value types. Is there anyway to do this?


Solution

  • There are no constraints on type T, so it can be a value type.
    You can rewrite method definition as

    protected T GetValue<T>(Expression<Func<T>> property, T defaultValueIfNull = default(T));
    


    Which will mean null for reference types and default value for value types.