Search code examples
c#if-statementswitch-statementtypeof

C# Switch For Types Of A Class


I have the following method which takes a type of class as a parameter:

public void test(Type proType){

}

I currently have a large if else which looks like:

if(proType == typeof(Class)){}

As there is about ten this looks untidy.

I tried turning this in to a switch but couldn't get it to work.

Is there any better practice to this or away to get a switch statement to work?

           switch (proType)
            {
                case typeof(ClassName):
                    break;
            }

"A constant value required"

The function is been called like test(typeof(class))

So the aim is i have a Big object which contains many small classes.

The typeof(class) switch/if statement allows me to decide what container to go in to get the objects out.


Solution

  • So, how about making all the objects that you are testing share a common interface?

     interface ITestable
     {
         void DoSomething();
     }
    

    and each object implements this interface differently:

     class MySomething : ITestable
     {
         public void DoSomething()
         {
             //type specific implementation
         }
     }
    
     class MyOtherSomething : ITestable
     {
         public void DoSomething()
         {
             //type specific implementation
         }
     }
    

    Now:

     foreach(ITestable testable in myTestablesList)
     {
         testable.DoSomething();
     }
    

    and all your switching logic disappears. Tada!