Question

What is the better alternative to use of if/then in the following logic:

    public void DoSomething <T>()
    {
        if (typeof (T) == typeof (A))
        {

        }
        else if (typeof (T) == typeof (B))
        {

        }

    }
Was it helpful?

Solution

You could probably overload the method instead:

public void DoSomething(A item)
{
   ...
}

public void DoSomething(B item)
{
   ...
}

OTHER TIPS

You're right that is a code smell.

Something like:

public void DoSomething <T>() where T : A
{

}

public void DoSomething <T>() where T : B
{

}

If you are doing this though, then it stuill feel a bit smelly. A better solution would to have both A & B inherid a common interface and then have a single method where T : IMyNewInterface.

If that's really not possible then this might not be a problem to solve this way, or the architecture might need revisiting.

CORRECTION

The above code is not valid, as Eric stated in the comment below. Generics do not form part of the signature, so can't be used in a overload.

The only other option is a normal overload:

public void DoSomething(A a)
{

}

public void DoSomething(B b)    {

}

You probably want your objects to be of a similar type or have similar method naming when you're using generics.

With what you've described, this is my preferred pattern:

public void DoSomethingA() { }
public void DoSomethingB() { }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top