0

Working with <Nullable>enable</Nullable>, how can I fix KO method to allow expression1 as parameter?

public class X
{
    public DateTime? dummy {get; }
}

public static class G
{
    //   Why this doesn't solve the issue?   -- \    
    //                                          |
    //                                          v
    public static void KO<T>(Expression<Func<X,T?>> p) {}
}

[Fact]
public void Test1()
{
    Expression<Func<X,DateTime?>> expression1 = x => x.dummy;
    G.KO<DateTime>(expression1);
    // error CS1503: Argument 1: cannot convert from 
    // 'System.Linq.Expressions.Expression<System.Func<gengen.UnitTest1.X, System.DateTime?>>' to 
    // 'System.Linq.Expressions.Expression<System.Func<gengen.UnitTest1.X, System.DateTime>>'
}

I know some solutions are using ! (for example on EF). But Expression<Func<X,DateTime>> expression1 = x => x.dummy! also doesn't work for me

dani herrera
  • 48,760
  • 8
  • 117
  • 177
  • I don't think you can use T? because T may already be something like object?, so that would mean you would be specifying object??, which has no meaning. – jmcilhinney Feb 17 '23 at 12:57
  • `T?` is a completely different type depending on whether `T` is a reference or a value type. Adding a `where T : struct` constraint to `KO` will allow for it. – Jeroen Mostert Feb 17 '23 at 12:59
  • @JeroenMostert, yes, was this. Can you write as answer, please? – dani herrera Feb 17 '23 at 13:00
  • I'm hesitant to do so because it's not clear that's the right approach; the method then cannot be applied to non-null value types or reference types. Adding overloads can solve that, but whether *that's* what's needed in this case is another matter. If it is the right answer for your super-genericized scenario feel free to write it up yourself. – Jeroen Mostert Feb 17 '23 at 13:02
  • Nullable does not work well with generics in my experience. The workarounds I'm aware of is to use generic restrictions to create separate methods for struct/class. Or to use a custom `Maybe`. See for example [Nullable type as a generic parameter possible?](https://stackoverflow.com/questions/209160/nullable-type-as-a-generic-parameter-possible) for a possible duplicate – JonasH Feb 17 '23 at 13:06
  • @JeroenMostert, I know why you don't want to write answer :) https://stackoverflow.com/a/36775837/842935 Drop and run. – dani herrera Feb 17 '23 at 13:33

0 Answers0