Sunday, May 16, 2010

C#: Making sure parameter has attribute

Programmer Question

I have an attribute lets call it SomeAttribute and a class i need to make sure the class is passed a type which has SomeAttribute. So this is how i do it now:



public class Test()
{
public Test(SomeType obj)
{
if(!obj.GetType().IsDefined(typeof(SomeAttribute), false))
{
throw new ArgumentException("Errormessage");
}
}
}


But this means that i don't get any errors at compile time but somewhere at runtime, if obj does not have the attribute. Is there a way to specify in the method declaration that the parameter must have some attribute ? So i get errors i compile time when using the wrong parameters, or do i have to use an empty interface ?



EDIT: I think the easiest solution would be an empty interface.



Find the answer here

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails