Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - switch in generics

Tags:

c#

generics

I tried to compare a generic-typed parameter over a switch within a generic method. That doesn't work for me with my solution. The reason: the parameter must be a specific type (bool, char, string, integral, enum).

    public T testfunction<T, U>(U numb)
    {
        switch(numb){ //<-- error

        }
        ....
    }

But what's the sense behind it? If the parameter is generic and I want to do a comparison, why does it have to be a type defined variable?

like image 691
lufonius Avatar asked Jun 13 '26 06:06

lufonius


2 Answers

What are you trying to test in your switch statement? Surely you must know SOMETHING about the type of object that is coming in.

Consider: how would you structure a switch statement when you could accept either a Product or a Customer type in your method? What is the logical choice that you want the compiler to make for you? If you want the compiler to choose an action based on the price of a product, that doesn't work for Customer objects. However, if both Products and Customers have a CreateDate field that you want to pivot on, you could extract that into an interface and use that as a generic constraint on the method.

Add an appropriate constraint to your generic method signature that encapsulates what you do know about the types that you expect, and then you will be able to switch:

public interface ICreateDate {

   public DateTime CreateDate { get; set; }

}

 public T testfunction<T, U>(U numb) where U : ICreateDate
    {
        switch(numb.CreateDate.DayOfWeek){

            case DayOfWeek.Monday:

        }
        ....
    }
like image 131
Jeff Fritz Avatar answered Jun 14 '26 20:06

Jeff Fritz


This does not work because the case sections inside of the switch need to be compile-time constants of a specific type. For example, you couldn't do case 1: because numb could be a string; neither can you do case "foo": because numb could be an integer. The type of numb must be known at compile-time in order to use it as the switch variable, because the compiler needs to know what kinds of constant values are valid in the case sections.

like image 34
cdhowie Avatar answered Jun 14 '26 18:06

cdhowie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!