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;
}
}