Question

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.

Was it helpful?

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!

OTHER TIPS

What is it that you are really trying to achieve. I would guess that 9 out of 10 times, when you are switching over the type of some object, your design is flawed. Virtual dispatch or polymorphism (or both) are what you are really looking for in most of these cases, but without knowing what the problem is that you are trying to solve, one cannot say for certain.

I normally go with a Dictionary to create a cache of actions to take for each type; load it up at startup if types are known up front, or use TryGetValue and populate when it fails.

You can use switch(Type.GetTypeCode(proType)) if the types you're interested in are in the TypeCode enum. For example, from the docs:

static void WriteObjectInfo(object testObject)
{
    TypeCode    typeCode = Type.GetTypeCode( testObject.GetType() );

    switch( typeCode )
    {
        case TypeCode.Boolean:
            Console.WriteLine("Boolean: {0}", testObject);
            break;

        case TypeCode.Double:
            Console.WriteLine("Double: {0}", testObject);
            break;

        default:
            Console.WriteLine("{0}: {1}", typeCode.ToString(), testObject);
            break;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top