0

Let's say I have this code like this....

public void SayType<T,E>(Func<T, E> f)
{

    var dataType = string.Empty;
    if (typeof(E) == typeof(DateTime))
        dataType = "date/time";
    else if (typeof(E) == typeof(string)) 
        dataType = "text";
    else if (typeof(E) == typeof(int)) 
        dataType = "whole number";
   
    Console.WriteLine($"type identified as {dataType}");
}

Is there a way to rewrite this with pattern-matching? E.g. something like:

 //Note this won't compile since the LHS of a case must be a const.
 var dataType = typeof(E) switch {
      typeof(DateTime) => "date/time",
      typeof(string) => "text",
      typeof(int) => "whole number",
 };

This github proposal may be relevant but I could just be reading too much into it.

NeilMacMullen
  • 3,339
  • 2
  • 20
  • 22
  • Since generic type parameters are resolved at compile time, you could just as well overload the methods: `public void SayType(Func f)`, `public void SayType(Func f)` and `public void SayType(Func f)`. – Olivier Jacot-Descombes Jan 24 '23 at 15:43

1 Answers1

2

is requires an instance which will be type-tested so it will not be useful here. You can try a bit hackish approach with case guards:

var type = typeof(E);
var dataType = true switch
{
    _ when type == typeof(DateTime) => "date/time",
    _ when type == typeof(string) => "text",
    // ....
    _ => string.Empty
}; 

But it can be considered too hackish due to the tested value being ignored in the switch expression arms.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • I didn't understand your last sentence. – Robert Harvey Jan 24 '23 at 14:54
  • 1
    @RobertHarvey in `true switch` `true` is ignored (not tested/checked) by switch cases . – Guru Stron Jan 24 '23 at 14:55
  • @RobertHarvey `var type = typeof(E);` – Guru Stron Jan 24 '23 at 14:58
  • I'd like a bit more information about why you consider this hackish. Is there any peril here, other than it being a bit obtuse? – Robert Harvey Jan 24 '23 at 15:00
  • @RobertHarvey cause it breaks the original intent of the `switch` expression - to pattern match with the input expression. Again, personally I'm actually fine with such usage but I see the validity in argument this being not the cleanest code. – Guru Stron Jan 24 '23 at 15:04
  • 1
    Thanks Guru - fwiw agree on the slight "hackish" element of having to encode the type in the condition but still an improvement over the nested if/then I think. Another imperfect approach is to just use a lookup table of course.. debatable which is clearer.. – NeilMacMullen Jan 25 '23 at 10:49