C#: Making sure parameter has attribute

Posted by slayerIQ on Stack Overflow See other posts from Stack Overflow or by slayerIQ
Published on 2010-05-16T20:14:39Z Indexed on 2010/05/16 20:20 UTC
Read the original article Hit count: 296

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about c#

Related posts about attribute