some reflection questions

  • Thread starter Thread starter memememe
  • Start date Start date
M

memememe

I am using the Activator class and creating an instance by passing the type
I want to create and the paramters for the constructors.
My question is:
Lets assume we got Interface A, and Interface B, and a class C that
implements both.
If I have two contructors, one takes an instance of a class that implements
A and the other an instance of a class that implements B.
If I try to create an instance passing class C as my parameter, which
constructor will be called?
I could probably tried hte test in the time I typed this, ohhh well.
 
One of the overloads of the Activator.CreateInstance also takes an array of
objects that will be passed to the contructor. It will look for a
constructor that matches the correct order and types of the elements of the
array. So, if your array has an element of type InterfaceA it will call the
contrstructor that takes it. The same is true if you use InterfaceB

HTH
 
I have just tried it.
public interface A
{
String A();
}
public interface B
{
String B();
}
public class C :A,B
{
public String A()
{
return "a";
}
public String B()
{
return "b";
}
}
public class Test
{
public Test(A a)
{
Console.WriteLine("A");
}
public Test(B b)
{
Console.WriteLine("B");
}
}

and the code that calls all this:
C c = new C();
Object[] ob = new Object[1];
ob[0] = c;
Test t = (Test)System.Activator.CreateInstance(typeof(Test),ob);

Whenver the constructor is called by the Activator create instance method,
the constructor that gets called is Test(A a) rather than Test(B b)
eventhough both constructors would apply. This woudnt happen if I just do a
new Test(c) because it would give a compile time error.
I do emphasize that I have no real reason to why I need this, I was just
playing with reflection and that idea poped in my head.
 
Back
Top