Accessing Parse method for arbitrary Type

  • Thread starter Thread starter Bob Rundle
  • Start date Start date
B

Bob Rundle

I would like to get something like this to work...

Type t = FindMyType(); // might be int, float, double, etc
string s = "1233";
object v = t.Parse(s);

This doesn't work of couse, Parse is not a member of Type.

I have to think that this is possible. Is it?

Regards,
Bob Rundle
 
Hmm, only way I could think of would be something like this:

Type t = FindMyType(); // might be int, float, double, etc
object v = null;
if (t == typeof(double))
v = double.Parse(s);
else if (t == typeof(int))
v = int.Parse(s);
.... etc

Maybe someone else knows a better way?
 
The only other way I could think of to do it (if you want to get rid of the if's) would be to use reflection to get the Parse
method.
Code modified from:
http://www.c-sharpcorner.com/Code/2003/Oct/LateBindingWithReflection.asp
Check MSDN for the MethodInfo and BindingFlags, I think you'll need another using statement (or fully specify it here in the code
itself).

MethodInfo mi;
object result = null;
object[] args = new object[] {"ABC123"};
Type t = FindMyType(); // might be int, float, double, etc
mi = t.GetMethod("Parse");
if (mi != null)
{
result = t.InvokeMember ("Parse", BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Static, null, null, args);
}


Not sure if that would be considered any "cleaner" though.
 
Back
Top