[.net] Validating Attribute Constructor Input?

Started by
0 comments, last by mutex 16 years, 1 month ago
I'm working on a project and finally have a really good use for some custom attributes. Trouble is that I want to do some validation on the input of the constructor for the attribute. Basically this is what I want to have:

    [AttributeUsage(AttributeTargets.Class)]
    public class RequiredDataProviderAttribute : Attribute
    {
        Type dataProviderType;

        public Type DataProviderType
        {
            get { return dataProviderType; }
        }

        public RequiredDataProviderAttribute(Type type)
        {
            if (!typeof(IDataProvider).IsAssignableFrom(type))
                throw new Exception("Type is not derived from IDataProvider.");

            dataProviderType = type;
        }
    }

However that exception isn't thrown at compile time or runtime. Is there any way to make a validation like that and have it enforced? I would prefer to catch it at compile time, but either really works for me.
Advertisement
It looks like the attribute object is constructed when you try to retrieve it, and so the exception will occur at runtime:

[Asdf(null)]class Program{    static void Main(string[] args)    {        Type type = typeof(Program);        object[] attrs = type.GetCustomAttributes(false);        foreach (Attribute attr in attrs)        {            Console.WriteLine(attr.GetType().Name);        }    }}[AttributeUsage(AttributeTargets.All)]public class AsdfAttribute : Attribute{    public AsdfAttribute(string text)    {        if (text == null)            throw new ArgumentNullException("text");    }}


Running results in ArgumentNullException thrown by AsdfAttribute inside the GetCustomAttributes call:

> TestAttribute.AsdfAttribute.AsdfAttribute(text = null) Line 29 C#
[Native to Managed Transition]
[Managed to Native Transition]
System.Reflection.CustomAttribute.CreateCaObject(module, ctor, blob = 11675394, blobEnd, namedArgs = 0) + 0x69 bytes
System.Reflection.CustomAttribute.GetCustomAttributes(decoratedModule = {TestAttribute.exe}, decoratedMetadataToken = 33554434, pcaCount = 0, attributeFilterType = {Name = "Object" FullName = "System.Object"}, mustBeInheritable = false, derivedAttributes = null) + 0x1eb bytes
System.Reflection.CustomAttribute.GetCustomAttributes(type, caType, inherit) + 0x103 bytes
System.RuntimeType.GetCustomAttributes(inherit) + 0x2e bytes
TestAttribute.Program.Main(args = {string[0]}) Line 14 + 0x9 bytes C#

This topic is closed to new replies.

Advertisement