dimanche 29 décembre 2019

C# Is there any better way to use Switch-Case / If-Else on generic types

I am currently trying to get some casting on generic types done. So the base idea is to have a method which accepts a generic Type and does different stuff depending on which type gets passed in.

For simplicity reasons I will just showcase the use of float, bool and default

The setup looks something like this (where T is a generic type defined by the class itself):

protected T DoStuff(T value)
{
   switch (value) {
      case float floatValue:
         float result = DoFloatStuff(floatValue);
         switch (result) {
            case T output:
               return output;
         }
      case bool boolValue:
         bool result = DoBoolStuff(boolValue);
         switch (result) {
            case T output:
               return output;
         }
      default:
         return value;
   }
}

Where DoFloatStuff and DoBoolStuff are just methods that have 1 parameter and a return type of their types respectively.

If I don't do it like that (I tried some typeof() casting before), the compiler always complains that it cannot cast from T to float and vice versa, even tho I made sure that would be the case with some Case-Switch / If-Else statements.

Does anybody know some better way to do this?

Thanks in advance, BOTHLine

Edit: Since a lot of people said kind of the same thing, that I either shouldn't use generics at all in a case like that or my methods would need to be more generic themselves.. My problem here is that I need to use 3rd party methods to handle the special cases I'm checking for (in this case the float and bool types). For the default case I already handled everything in a generic way. But for some defined types I just can't do that.

So to go a little more in detail why that's the case: I'm currently working on a Plugin for the "Unity Engine". Unity has built in methods to display types (kind of all primitive types and some Unity-specific types). I have a generic Wrapper class which should be able to contain any types. But then when I want to display the content of that wrapper in the GUI that Unity Editor offers, I have to use the built-in methods to display the primitives (something like UnityEditor.EditrGUI.FloatField()). Without those methods I am never able to display anything. Anything else which can be broken down to those types can then be displayed in a more generic way.

Aucun commentaire:

Enregistrer un commentaire