views:

946

answers:

3

Hi,

while writing a custom attribute in C# i was wondering if there are any guidelines or best practices regarding exceptions in attributes. Should the attribute check the given parameters for validity? Or is this the task of the user of the property?

In a simple test I did the exception was not thrown until i used GetCustomAttributes on a type with an exception throwing attribute. I just think it's a bit awkward to get an exception from an Attribute only when explicitly asking for them.


Example Attribute with exception:

[AttributeUsage(AttributeTargets.Interface, AllowMultiple = false, Inherited = false)]
sealed public class MyAttribute : Attribute
{
    public string SomeValue { get; private set; }

    public MyAttribute(string someValue)
    {
     if(string.IsNullOrEmpty(someValue))
     {
      throw new ArgumentNullException("path");
     }

     if(!someOtherCheck(someValue))
     {
      throw MyAttributeException("An other error occured");
     }

     SomeValue = someValue;
    }
}
+5  A: 

Attributes are only actually constructed when you use reflection, so that's the only time you can throw an exception. I can't remember ever using an attribute and having it throw an exception though. Attributes usually provide data rather than real behaviour - I'd expect the code which uses the attribute to provide any validation. I know this isn't like normal encapsulation, but it's the way it tends to be in my experience.

Jon Skeet
A: 

We have some reasonably complex Attributes in our project, so we include validation of inputs. For example, as part of our I18N and L10N work, we have attributes that perform resource lookups (much like the attributes in the framework that are used to localise Category and Description strings for properties in the designers). These custom attributes have to have some validation in order for them to work.

The simple attributes we have use no validation because we'd rather the consuming code failed, indicating the location of the error.

So, in conclusion, it really depends on the complexity of the attribute; if it is instantiated with one kind of data but expected to provide another (such as in resource lookups), it should contain validation, otherwise, it probably shouldn't.

Jeff Yates
+1  A: 

With a few exceptions with compiler-sepcific meaning (such as [PrincipalPermission] etc) attributes can't interact directly with code without being asked to. However, if you use the AOP tool "PostSharp", your aspect attributes can add behaviour to the class. Not simple, but a very useful trick sometimes.

Marc Gravell