I have a C# method say:
MyMethod(int num, string name, Color color, MyComplexType complex)
Using reflection, how can I distinctly identify each of the parameter types of any method? I want to perform some task by parameter type. If the type is simple int, string or boolean then I do something, if it is Color, XMLDocument, etc I do something else and if it is user defined type like MyComplexType or MyCalci etc then I want to do certain task.
I am able to retrieve all the parameters of a method using ParameterInfo and can loop through each parameter and get their types. But how can I identify each data type?
foreach (var parameter in parameters)
{
//identify primitive types??
//identify value types
//identify reference types
}
Edit: this is apart of my code to create a propert grid sort of page where I want to show the parameter list with data types for the selected method. If the parameter has any userdefined type/reference type then I want to expand it further to show all the elements under it with datatypes.
Make use of ParameterInfo.ParameterType
If you need to check the
System.Type
once retrieved you can useIsPrimitive
andIsByRef
as mentioned by David. In addition you can also useIsValueType
. There are a significant number of Is* properties within the System.Type class. Your best bet would be to check the MSDN documentation on each Is* property ie...IsClass
states...Therefore one could deduce that
IsValueType
does not need to be called. Keep in mind that a given type can return true across multiple properties in thatIsClass
could return true ANDIsPassByRef
could return true. Perhaps provide logic for the known CLR types since those will not change and you know those ahead of time and then build in the logic for complex types as defined by the user. You could take the approach of building in the logic to do this for the CLR types as well; either way would work.To get the actual
Type
of the parameter use theParameterType
on theParameterInfo
value. With that value there are several ways you can use it to identify the type. The easiest is with a direct comparison to a known typeOr in cases where the type is not available a name match can be used (although this is a bit flakier as refactor operations may miss the string constant and silently break the application)