Similar question: Passing int list as a parameter to a web user control
Is there any similar example for enum type?
I am creating a asp.net custom control in which I want to pass comma separated list of enums as property.
I am writing a TypeConverter for converting comma separated string values to List of Enum.
In the ConvertTo method,
How to create InstanceDescriptor object for list of enum?
My current code is as follows:
//enum
public enum MyEnum {Hello, World}
//main method
List<MyEnum> list = new List<MyEnum>();
list.Add(MyEnum.Hello);
list.Add(MyEnum.World);
ConstructorInfo constructor = typeof(List<MyEnum>).GetConstructor( Type.EmptyTypes );
InstanceDescriptor idesc = new InstanceDescriptor(constructor, list);
This fails with the message
Length mismatch
I wonder why
The "Length mismatch" error occurs because you retrieve the default
List<T>constructor, which has ZERO arguments, and then you askInstanceDescriptorto call that constructor with TWO arguments,MyEnum.HelloandMyEnum.World.You might think that you could use the alternate
List<T>constructor that accepts a singleIEnumerable<T>argument:This makes
InstanceDescriptorhappy, but unfortunately, you'll find that ASP.NET now throwsNullReferenceExceptioninstead (same as in the question you linked to) because ASP.NET doesn't know how to deal withIEnumerable<T>parameters.Here are two ways to solve the problem.
Solution 1: Change your custom control and your type converter to use
MyEnum[]instead ofList<MyEnum>. This works because ASP.NET can handle arrays.Solution 2: Create a static helper method that creates a
List<MyEnum>from an array:Then change your type converter to create an
InstanceDescriptorthat calls the helper method, passing it your list as an array: