Activator.CreateInstance with implicit type conversion

  • Thread starter Thread starter alp
  • Start date Start date
A

alp

Hi,

I've got a class constructor that takes

public Foo(int a, MyString b)

MyString type has an implicit operator for string so I can call this
from code with Foo f = new Foo(1, "hello");

However i'd like to programmatically call the constructor using

Activator.CreateInstance(typeof(Foo), new object[] { 1, "hello" })

This doesn't work because the constructor is of type MyString, and the
CreateInstance Binder is looking for a type string. Is there anyway to
get the Binder to just 'use' the params I pass in, or at least to see
if there is a possible implicit type conversion possible???
Cheers,

Al
 
You might be able to do that *somewhat* using reflection. Look into
ConstructorInfo class. Is that what you were looking for?
 
Another solution may be subclassing the Binder, and passing this to the
overloaded Activator.CreateInstance that takes Binder param.
 
Hi,
The implicit type conversion is a mechanism supported by C# compiler, not
CLR. So I think that you would have to do it by yourself through reflection.
At least, you would have to data mine whether there is a direct type
conversion constructor for MyString that accepts a string parameter, then
invoke the constructor and get the MyString reference needed for the
reflection call.

Regards
Ming Chen
 
Ming said:
Hi,
The implicit type conversion is a mechanism supported by C# compiler, not
CLR. So I think that you would have to do it by yourself through reflection.
At least, you would have to data mine whether there is a direct type
conversion constructor for MyString that accepts a string parameter, then
invoke the constructor and get the MyString reference needed for the
reflection call.

Regards
Ming Chen

Hmm, the problem is that the use of CreateInstance is in a factory
class which i'd like to keep generic rather than use specific mining
through reflection to find an appropriate constructor and
implicit/explicit type conversion routine.

Al
 
If I invoke ConstructorInfo.Invoke(object[] args) it fails with the
same error as above, the Binder is looking for the explicit parameter
match :(

Thanks,
Al
 
I've tried this but the Binder class is abstract and the documentation
doesn't tell me which class implements the default Binder so that I
could subclass it. I tried using the Binder implementation given in the
docs and quoted various times on the web, but even with a modified
CanConvert method it fails and i'm concerned that by implementing my
own type rather than subclassing the built-in type I may end up not
implementing all the built-in functionality.

Thanks,
Al
 
Back
Top