gm9089zo
gm9089zo

Reputation: 19

C# Simple Type w/ Generic Type

I want to do different things with a generic type given that it is a byte array, int, etc.

    public void GenericType<T>(T Input)
    {
        switch (typeof(T))
        {
            case (typeof(byte[])):
                break;
            case (typeof(int)):
            case (typeof(float)):
            case (typeof(long)):
                break;
            case (typeof(string)):
                break;
            default:
                throw new Exception("Type Incompatability Error");
                break;
        }
    }

Sandbox.cs(12,13): error CS0151: A switch expression of type `System.Type' cannot be converted to an integral type, bool, char, string, enum or nullable type

add:

My specific case has some code that is generic and some code that is specific. I also have one where I do not actually pass a T variable. Solutions thus far work if there is a variable.

    public void GenericType<T>()

Not being terribly experienced, what is the best practice in C#?

Thank you.

Upvotes: 0

Views: 69

Answers (2)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

You can do this with switch using pattern matching:

switch(Input)
{
   case int i:
      // do something with i
   case string x:
      // do something with x
}

Upvotes: 2

No Refunds No Returns
No Refunds No Returns

Reputation: 8336

You might try something like

if (Input is int i) { DoSomething(i) ; }
else if (Input is long l) { DoSomething(l) ; }

Best? Maybe. Works? Yup.

You are effectively calling System.Object GenericType in this example.

Upvotes: 1

Related Questions