18

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?

Mohit S
  • 13,723
  • 6
  • 34
  • 69

2 Answers2

28

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.

Mikhail Tulubaev
  • 4,141
  • 19
  • 31
  • 1
    actually, if you are not going to pass value types to this method, will be better to add constraint on method or (if type T is defined by class) on class. – Mikhail Tulubaev Sep 23 '15 at 06:44
10

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.

C.Evenhuis
  • 25,996
  • 2
  • 58
  • 72