Click here to Skip to main content
15,893,487 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi folks! I've coded myself into another corner... again! I need a guru.

This time, I'm writing code that checks that the parameter list for a call to a method is valid. Why? Because I am dynamically calling various methods with parameters read from an XML file. Why? Don't ask... looooong story.

Breifly, a call to my routine might look like
StandardTest.PerformDALvsDBTest(<br />  "DALRoutines",    // the class that will contain the method to call<br />  "InsertCustomer", // the method to be called<br />  new object[] { <br />    DateTime.Parse(parm0), <br />    parm1, <br />    Int32.Parse(parm2)<br />  }<br />);


Okay. So my routine goes through a bunch of checks and finally obtains a reference to the method to be called (MethodInfo.methodRef). The call to the method will be made using
methodRef.Invoke(null, myBindings, null, Params, null);

But first, I must make sure that all the items in the object[] Params are of the right type. To do that I loop through methodRef.GetParameters() and check each one against each Params[index].GetType().
If there are the correct number of parameters, and they are all of the correct type, etc, then I will perform the Invoke(), otherwise, I throw an error indicating the method name, the parameter, the expected type and the type that was used:
e.g. "The System.Type for parameter #0 in the parameter list for the method [DALRoutines.InsertCustomer] is System.DateTime; System.TimeSpan was expected".

So, here is my problem:
I have a method that expects a parameter to be an Int32. However, when the value is passed in the object[] Params, it seems to be changed to Int16 (even if I specifically indicate that it is Int32 as above - I assume that it is because it is a small value). When my routine starts comparing parameter types it spits out an error saying it was passed an Int16 when it expects an Int32. The kicker is that the call to Invoke() would still work if it was made - .NET does not seem to mind and handles the conversion inherently. But I can't find a way to tell that it would work - all I can see is that the two types are different.

I have tried investigating different ways to tell if the types are compatible (including Type.IsSubclassOf() and Type.IsAssignableFrom()) but I can't seem to find anything that will let me know that an Int16 can be used as the value for an Int32 parameter.

Does anyone know a way to do this?

Posted

1 solution

Would something like this be okay?

<br />		public static bool ImplicitCastAllowed(Type type, object value)<br />		{<br />			try<br />			{<br />				Convert.ChangeType(value, type);<br />				return true;<br />			}<br />			catch<br />			{<br />				return false;<br />			}<br />		}<br />


regards
 
Share this answer
 


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900