Arjang Arjang - 1 year ago 51
C# Question

How to put constructor expressions in an array an use them in C#?

Suppose class

are both inheriting from class
Suppose We have an array of constructor expressions (not sure what code for that is) of A and B so that (psudo code)

a[0] = new X();
a[1] = new Y();

How can we get :
P p = Execute(a[0]);

Answer Source

You can create an Func<P> delegate array for the constructors. For example:

Func<P>[] a = new Func<P>[2];
a[0] = () => new X();
a[1] = () => new Y();
P p = a[0]();

The above example covers default constructor calls. More complex constructor calls can be made by creating an object to hold constructor values and then changing the array to take the object. For example, lets say there is a class Z with properties val1 and val2. This can be done:

Func<Z, P>[] a = new Func<Z, P>[2];
a[0] = z => new X(z.val1, z.val2);
a[1] = z => new Y();
Z varZ = new Z(1, 2); // For example
P p = a[0](varZ);
P p1 = a[1](null);