I was playing with attributes and reflection when I found a strange case. The following code gave me an exception at runtime when I try to get constructor arguments of custom attributes.
using System;
using System.Reflection;
class Program
{
[Test(new[] { Test.Foo }, null)]
static void Main(string[] args)
{
var type = typeof(Program);
var method = type.GetMethod("Main", BindingFlags.Static | BindingFlags.NonPublic);
var attribute = method.GetCustomAttributesData()[0].ConstructorArguments;
Console.ReadKey();
}
}
public enum Test
{
Foo,
Bar
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class TestAttribute : Attribute
{
public TestAttribute(Test[] valuesOne, Test[] valuesTwo)
{
}
}
The problem seems to be the parameters passed to the Test attribute constructor. If one of them is null, ConstructorArguments throw an exception. The exception is ArgumentException with name as exception message.
Here is the stack trace from ConstructorArguments call:
System.RuntimeTypeHandle.GetTypeByNameUsingCARules(String name, RuntimeModule scope)
System.Reflection.CustomAttributeTypedArgument.ResolveType(RuntimeModule scope, String typeName)
System.Reflection.CustomAttributeTypedArgument..ctor(RuntimeModule scope, CustomAttributeEncodedArgument encodedArg)
System.Reflection.CustomAttributeData.get_ConstructorArguments()
If I set a non null value to each parameters there is no exception. It seems to only happen with enum array. If I add another parameter such as string and set them to null, there is no problem.
A solution could be to always pass a value such as an empty array but here I would like to keep the ability to pass null value because it has a special meaning in my case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With