Zack Marrapese
Zack Marrapese

Reputation: 12080

detecting type of generics within generics

I have a method which accepts many different types of objects for storage:

public void Store<T>(T item)
{
    // works fine
    if (item is Foo)
    {
      // ...
    }
    // works fine
    else if (item is Observation<ImageSignal>)
    {
      // ...
    }

    // isn't detected
    else if (item is Observation<Signal<ISpectrum>>)
    {
      // ...
    }

    else 
    {
      // Observation<Signal<ISpectrum>> always hits this.
      throw new NotSupportedException();
    }
}

Can anyone tell me how I can detect this?

EDIT: I was actually passing in an object which wraps this object. Eric was right. Problem solved. Thanks for the quick responses, however.

Upvotes: 1

Views: 77

Answers (2)

Ventsyslav Raikov
Ventsyslav Raikov

Reputation: 7192

typeof(T) or item.GetType(). hth

Upvotes: 0

Magnus
Magnus

Reputation: 46909

In this case wouldn't it be better to overload the Store function? It would be much easier to follow the logic.

public void Store(Foo item)
{
}

public void Store(Observation<ImageSignal> item)
{
}

public void Store(Observation<Signal<ISpectrum>> item)
{
}

Upvotes: 5

Related Questions