Domanda

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))
        {

        }

    }
È stato utile?

Soluzione

You could probably overload the method instead:

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

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

Altri suggerimenti

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() { }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top