C# Generic parameters - is there any "nullable or not" constraint

116 Views Asked by At

I'm often building tools with generics and Expression<Func<object, value>> to target properties of the object. I keep struggling on a very stupid limitation of C# (but maybe I am ignorant of the proper solution).

Let's say we have this object:

class MyObject {
  public int NeverNull { get; set; }
  public int? CanBeNull { get; set; }
}

I want to be able to do this:

int? val1 = Foo(o => o.NeverNull);
int? val2 = Foo(o => o.CanBeNull);

I have 2 solutions to do this :

// Solution 1: two overloads
// First overload: for the non-nullable properties
TValue? Foo<TValue>(Expression<Func<MyObject, TValue>> selector)
  where TValue: struct
{ ... }

// Second overload: for the nullable properties
TValue? Foo<TValue>(Expression<Func<MyObject, TValue?>> selector)
  where TValue: struct
{ ... }

And

// Solution 2: using object
TValue? Foo<TValue>(Expression<Func<MyObject, object>> selector)
  where TValue: struct
{ ... }

The first solution implies doubling the logic, which is meh. The second solution implies weak-typing issues and useless boxing/unboxing.

Is there a third, cleaner solution to have a 'nullable-or-not' generic parameter ?

0

There are 0 best solutions below