How to retrieve values from an array assigned to object type

G

Guest

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());
}
 
J

Jeffrey Tan[MSFT]

Hi HairlipDog,

Thanks for your post.

Yes, with getting the array with System.Object type, we can get the benifit
of polymorphism. In order to get the element in the array, we can cast the
object into IList interface(which all array implemented). Then loop through
the list to get each element. Sample code listed below:
// 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;

if(obj.GetType().GetElementType()!=null)
{
IList il=obj as IList;
for(int i=0;i<il.Count ;i++)
{
Console.WriteLine(il.ToString());
}
}

Hope this helps.

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 
J

Jeffrey Tan[MSFT]

Hi HairlipDog,

Does my reply make sense to you? Is your problem resolved? Please feel free
to tell me, thanks

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top