How to check at runtime if a class implements certain interface?
Posted
by mare
on Stack Overflow
See other posts from Stack Overflow
or by mare
Published on 2010-04-19T10:06:52Z
Indexed on
2010/04/19
10:23 UTC
Read the original article
Hit count: 220
Let's say I have some content classes like Page, TabGroup, Tab, etc. Certain of those will be implementing my IWidgetContainer interface - it means they will geet an additional field named ContainedItems from the interface and some methods for manipulating this field.
Now I need to reflect the fact that some class implements this interface by rendering out some special custom controls in my ASP.NET MVC Views (like jQuery Add/Remove/Move/Reorder buttons).
For instance, TabGroup will implement IWidgetContainer because it will contain tabs but a tab will not implement it because it won't have the ability to contain anything.
So I have to somehow check in my view, when I render my content objects (The problem is, I use my base class as strong type in my view not concrete classes), whether it implements IWidgetContainer.
How is that possible or have I completely missed something?
To rephrase the question, how do you reflect some special properties of a class (like interface implementation) in the UI in general (not necessarily ASP.NET MVC)?
Here's my code so far:
[DataContract]
public class ContentClass
{
[DataMember]
public string Slug;
[DataMember]
public string Title;
[DataMember]
protected ContentType Type;
}
[DataContract]
public class Group : ContentClass, IWidgetContainer
{
public Group()
{
Type = ContentType.TabGroup;
}
public ContentList ContainedItems
{
get; set;
}
public void AddContent(ContentListItem toAdd)
{
throw new NotImplementedException();
}
public void RemoveContent(ContentListItem toRemove)
{
throw new NotImplementedException();
}
}
[DataContract]
public class GroupElement : ContentClass
{
public GroupElement()
{
Type = ContentType.Tab;
}
}
Interface:
interface IWidgetContainer
{
[DataMember]
ContentList ContainedItems { get; set; }
void AddContent(ContentListItem toAdd);
void RemoveContent(ContentListItem toRemove);
}
© Stack Overflow or respective owner