I have a component that implements a property called obj of type object.
The intent is that a user can pass in any value or array of values and I
will be able to retrieve the values.
If the user creates an array and passes it to the obj property, I'm having
trouble figuring out an easy way to obtain the values in the array without
using a conditional for each type.
Is there a built-in method to obtain the values of an array assigned to
object without a giant conditional for each system type?
The following code demonstrates the problem.
// Create an object
object obj;
// Create an array type
short[] sArray = new short[10] {1,2,3,4,5,6,7,8,9,0};
// Assign sArray reference to obj
obj = sArray;
// The next line prints out 'System.Int16[]' indicating that the type for
obj is a short array
Console.WriteLine(obj.GetType().ToString());
// However, the iteration that follows will result in a compiler exception
// error CS1579: foreach statement cannot operate on variables of type
'object' because 'object' does not contain a definition for 'GetEnumerator',
or it is inaccessible
foreach (short s in obj)
Console.WriteLine(s.ToString());
// I can use a giant conditional like the code shown below but it is
cumbersome and repetitive
// switch is not allowed on System.Type, so an if..else if is used
if (obj.GetType().GetElementType() == typeof(short))
{
foreach (short s in (short[])obj)
Console.WriteLine(s.ToString());
}