Activator.CreateInstance with optional parameters

Conrad Clark picture Conrad Clark · Jun 12, 2012 · Viewed 7.5k times · Source

Does anyone know how to instantiate a class using a constructor which has just 1 parameter that is optional?

I've tried both

(T)Activator.CreateInstance(typeof(T), new object[] { Type.Missing });

and

(T)Activator.CreateInstance(typeof(T), new object[] { });

To no success... I'm getting MissingMethodException

Answer

Conrad Clark picture Conrad Clark · Jun 12, 2012

This worked:

(T)Activator.CreateInstance(typeof(T), 
                    BindingFlags.CreateInstance |
                    BindingFlags.Public |
                    BindingFlags.Instance | 
                    BindingFlags.OptionalParamBinding,null, new object[] {Type.Missing },CultureInfo.CurrentCulture);