Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 839
Mohit S Avatar asked Sep 23 '15 06:09

Mohit S


2 Answers

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.

like image 164
Mikhail Tulubaev Avatar answered Oct 15 '22 22:10

Mikhail Tulubaev


T in this case might also be a value type, such as int, which cannot be null. You should specify a type constraint, limiting T to classes:

...T defaultValueIfNull = null) where T : class

An alternative would be using ...T defaultValueIfNull = default(T)) - you wouldn't need the constraint, but value types would become 0 by default, instead of null.

like image 40
C.Evenhuis Avatar answered Oct 15 '22 22:10

C.Evenhuis