Reflection Newbie question

  • Thread starter Thread starter Ron M. Newman
  • Start date Start date
R

Ron M. Newman

Greetings C# Sages,

I have two strings, one is a class name, the other is a value

String c = "System.Int32";
String v = "12";

I assume the class has a "parse" method.

I'd like to create an object of c class and call it's "parse" method which
gets a value as a string. Any ideas?

Ron
 
Something like this?

String c = "System.Int32";
String v = "12";
int i = (int)Activator.CreateInstance(Type.GetType(c));
i = Int32.Parse(v);

HTH,
Eric
 
Hi, Almost: I can't count on it being an integer, this was just an example.
It can be any class. I need to make sure if it has a "parse" method and then
(only then) activate it.

Thanks
ron
 
Gotta love reflection!

String c = "System.Int32";
String v = "12";

object o = Activator.CreateInstance(Type.GetType(c));
object b;

MethodInfo m = o.GetType().GetMethod("Parse", new Type[] {
typeof(string) });

if (m != null)
b = m.Invoke(o, new object[] { v });

-Eric
 
You would not need to create an instance ...

The parse methods are static that return an object of type c ...

First you would need to get the type .. this can be done using
Type.GetType(string) http://msdn2.microsoft.com/en-us/library/w3f99sx1.aspx

Once you have the type you would need to get a methodinfo representing the
parse method. You can do this using Type.GetMethod from the type object that
was returned to you in the previous step
http://msdn2.microsoft.com/en-us/library/05eey4y9.aspx since you know the
method is static you can identify this in your binding flags
http://msdn2.microsoft.com/en-us/library/system.reflection.bindingflags.aspx

You would then want to use
http://msdn2.microsoft.com/en-us/library/a89hcwhh.aspx MethodInfo.Invoke (on
the methodinfo returned from the last step) to call the method (the msdn
page includes an example of getting the return value).

Cheers,

Greg Young
MVP - C#
http://codebetter.com/blogs/gregyoung
 
Back
Top