5

While using reflection in C#, you're expected to pass an object[] of the parameters that are cast later on, I have a gui that lets the user input the parameters values in. I know what type of input they are expected to input, int, string, float, instance of custom object, etc... In the case of the argument being an array of some type, int[] foo[], its lets the user construct an array of that type, and add/remove elements.

What I don't know is how I can use the information (i know the type of the data is type t.) How can I construct an array t[], so that when its given to invoke, it can convert to that array type.

For example right now if i have a function that requires an array of integers as an argument, i am currently passing an object[] with another object[] inside it that is filled with integers, but you can't just cast object[] to int[] so the invoke fails.

I can not write a switch case as it's not possible to predict all possible types it could be (instances of some other class defined in a loaded dll, for example)

2 Answers 2

17

Are you looking for Array.CreateInstance? That's useful if you only know the type dynamically. If you know it statically but within a generic method, you can just use new T[10] or whatever the type parameter name is.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 jeez =O question was asked at 14:29:01Z, answered at 14:29:42Z!
Well, I'm new here so I don't have enough reputation to upvote you, but yes. This is exactly what I needed. Thank you very much!
@Steven: By this time of day the upvote is irrelevant to me, but the acceptance is appreciated, thanks :)
2

This does not answer the question but I felt it might be an advice worth mentioning.

If it is a method which can be called by passing an array of int as well as array of object it seems that you are implementing a type-free behaviour which can be expressed by generics.

I suggest to change it to a generic method using IEnumerable<T>. Of course, IEnumerable<T> cannot be accessed by index (while array can) but not sure this is what you really need there.

In conjunction with MakeGenericType, it can give you the flexbility you need.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.