I’m implementing a method in C# that takes a single argument of type object, e.g. SomeMethod(object argument). I need to pass a collection of multiple objects of varying type to this method. I can’t change the method signature because of interface restrictions.
I was thinking of sending an object array, object[] myArray = new object[2], but I want to strongly type each element of the array if possible. For example, I have two objects, one of type Foo and the other of Bar. I want to guarantee that myArray[0] is Foo and myArray[1] is Bar.
How would I do this? Would another collection type or creating a special class make more sense?
UPDATE: All good answers. Tuple looks the most generic way but as I said in the comment, I’m limited to 3.5. A struct would work but after a little research on using structs vs classes as arguments, there is a slight performance hit if you use a larger struct. (Source – see Benchmark section). So I’m going to go with a class. Thank you all!
An
Arrayis collection of objects of some type. So you cannot guarantee this. The only way to do this is to create a composite type, astructor aclass.But if your signature
SomeMethod(object argument)is fixed, you would still not be able to guarantee that statically inside that method. The best you can do is to externally make sure you are passing argument of the correct type.