Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activator.CreateInstance with optional parameters

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

like image 309
Conrad Clark Avatar asked Jun 12 '12 18:06

Conrad Clark


People also ask

How do I set optional parameters?

Using Optional Attribute Here for the [Optional] attribute is used to specify the optional parameter. Also, it should be noted that optional parameters should always be specified at the end of the parameters. For ex − OptionalMethodWithDefaultValue(int value1 = 5, int value2) will throw exception.

Can you make a parameter optional?

The definition of a method, constructor, indexer, or delegate can specify its parameters are required or optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters. Each optional parameter has a default value as part of its definition.

What is activator CreateInstance?

CreateInstance(ActivationContext, String[]) Creates an instance of the type that is designated by the specified ActivationContext object and activated with the specified custom activation data. CreateInstance(Type) Creates an instance of the specified type using that type's parameterless constructor.


1 Answers

This worked:

(T)Activator.CreateInstance(typeof(T),                      BindingFlags.CreateInstance |                     BindingFlags.Public |                     BindingFlags.Instance |                      BindingFlags.OptionalParamBinding,null, new object[] {Type.Missing },CultureInfo.CurrentCulture); 
like image 57
Conrad Clark Avatar answered Sep 28 '22 03:09

Conrad Clark