1

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{}
griegs
  • 22,624
  • 33
  • 128
  • 205
  • 1
    Is there a generic `ILocation` as well? What's the hierarchy? What is `ITopRestaurant`? – Jon Dec 16 '11 at 02:34
  • ITopRestaunt is simply an empty interface used to identify the type of ILocation this item is – griegs Dec 16 '11 at 02:35
  • Possible duplicate of http://stackoverflow.com/questions/503263/how-to-determine-if-a-type-implements-a-specific-generic-interface-type – moribvndvs Dec 16 '11 at 02:36
  • @HackedByChinese, saw that one but looks a little complex for what I thought should be a fairly straight forward thing to do kwim? – griegs Dec 16 '11 at 02:37

2 Answers2

2

You can simply do this:

if (item.trendItem is TopLocation<IRestaurant>) 
Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
1

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

}
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536