griegs
griegs

Reputation: 22760

Test if class inherits generic interface

I know there are a few questions on this already but I can't seem to get this to work.

I have a class like this;

public class TopLocation<T> : ILocation
{
    public string name { get; set; }
    public string address { get; set; }
}

When I create the class I specify whether it's an IRestaurant or IClub. No problem so far.

However, how do I test to see whether it's an IClub or IRestaurant in an if statement?

This fails;

if (item.trendItem is ILocation<ITopRestaurant>)

and this returns null

               Type myInterfaceType = item.trendItem.GetType().GetInterface(
                   typeof(ITopRestaurant).Name);

The reason I'd like this in an if statement is because it's sitting within an ascx page in an MVC application and I am trying to render the correct partial view.

edit

in response to the comment;

public interface ITopClub{}
public interface ITopRestaurant { }
public interface ILocation{}

Upvotes: 1

Views: 378

Answers (2)

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93424

You can simply do this:

if (item.trendItem is TopLocation<IRestaurant>) 

Upvotes: 2

Justin Niessner
Justin Niessner

Reputation: 245389

First of all, ILocation is not a Generic Interface so trying to test anything against ILocation<T> is going to fail. Your class is the Generic Type.

Second, you're trying to figure out if the type used as a generic argument to your Generic Type is a given interface. To do that, you need to get the Generic Type Arguments for the type and then perform the check against that type:

var myInterfaceType = item.trendItem.GetType().GetGenericTypeArguments()[0];

if(myInterfaceType == typeof(ITopRestaurant))
{

}

Upvotes: 1

Related Questions