My code to do this uses reflection and strings that I give it, instead of user input. Ultimately I would like the user to be able to say "float" "2.0" and have the computer say, yeah, that's a float, or "bool" "abc" to which the computer would say, that's no boolean it's heard of.
It would be simple enough to take the user input and convert it to a primitive type name, like "string" to "System.String", "float" to "System.Single", etc. (although if you know of a function to do that, that would be great too.)
Here's the code:
Console.WriteLine("1.0 => {0}", System.Single.Parse("1.0")); // this works fine.
Type t = Type.GetType("System.Single"); // for parsing floats
MethodInfo mi = t.GetMethod("System.Single.Parse"); // "ambiguous" if use "Parse"
object[] parameters = new object[] { "1.0" };
float f = (float)(mi.Invoke(null, parameters)); // get null exception here.
Console.WriteLine("Was succesfully parsed to: " + f);
But I keep getting a null exception on the second to last line. What's going on there?
To do the same without using reflection:
to avoid an exception for an invalid type, you could do:
Your
t.GetMethod
doesn’t work. The method is calledParse
, not what you wrote. It might no longer be ambiguous – but that’s only because it now finds no method and silently returnsnull
.To make the call unambiguous, you need to specify the expected parameter types: