views:

68

answers:

3

Hey all,

I'm working with reflection and when I get the parameters' list of a method, I need to examine all of them, when I find any one which its type is an array I need to avoid it, I mean array of any kind, so I used the following which doesn't work:

(!(parameter.GetType().Equals(Array)))

The error was that I'm using a type as a variable!! What can I do to accomplish that, any suggestions??

+1  A: 

You are using a type ('Array') as a variable. There is a difference between a variable of type 'System.Type' (represents a type) and an actual type. To convert a type to a System.Type you use typeof(type).

Now, you don't want all things that are type Array, but rather those objects that could be assigned to an object that is type Array (i.e. Array or its descendants). It's a little backwards but the way to do that is to see if the System.Type for Array is assignable from the System.Type for your variable's type.

So, as a general pattern you want to try something like this:

( !(typeof(Array).IsAssignableFrom(parameter.GetType())) )

However, as another answer shows, System.Type has an IsArray property which skips this for you, so long as you are dealing with an actual array (int[], bool[] etc.) and not a custom Array descendant (e.g. something like CustomArrayClass : Array).

Graphain
Both answers you wrote, didn't work they returned false!! I tired many types but it returns nothing but false !!
Shaza
It should return false? It has a ("!") which is what you want (if NOT an array?)
Graphain
I meant without the (!).Anyways, thanks for the base idea.
Shaza
+5  A: 

Try

(!(parameter.GetType().IsArray))

NOTE - from MSDN:

The IsArray property returns false for the Array class.

To check for an array, use code such as typeof(Array).IsAssignableFrom(type).

If the current Type represents a generic type, or a type parameter in the definition of a generic type or generic method, this property always returns false.

Meaning that if you have simple array declarations like int[], string[], etc etc, the IsArray is fine, but if not then you will have to use IsAssignableFrom().

code4life
A: 

As I'm using parameters, I shouldn't use "GetType", like this:

( !(typeof(Array).IsAssignableFrom(parameter.GetType())) )

This only works for assigned objects, with parameters this will return the type parameterInfo.

For parameters, "ParameterType" should be used and answer will look like this:

( !(typeof(Array).IsAssignableFrom(parameter.ParameterType)))
Shaza
You didn't mention that you were working with a parameterinfo. It was implied that parameter was the name of one of your parameters (e.g. an object passed in). Glad to see you worked it out anyway.
Graphain