By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
458,067 Members | 954 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 458,067 IT Pros & Developers. It's quick & easy.

passing integer array as object array

P: n/a
Hi all,
I am a new programmer to C# and i am having a following problem.
I want to make a single method which takes a variable length array and
display it contents.
i have defined the method as:

public void DisplayVals(params object [] objArray) {
foreach (object o in objArray)

I am sending it three types of array, one by one:
1. an integer list directly as parameter to the method.
eg. t.DisplayVals(2,4,6,8);
2. an integer array explicitly defined and then sent.
eg. int [] intArray = {1,2,3,4,5,6};
3. an user defined type, Employee which has overriden ToString()
eg. Employee [] empArray = new Employee[3];
then created the employee objects with for loop and,

In the first and third case the values are shown properly but in the
second case the output is: System.Int32[].
What can i do in the method DisplayVals or with the explicit array
intArray so that the conents of intArray can be displayed. I dont want
to overload DisplayVals method (one for the integers and one for the
user defined types).

The complete code is:

using System;
// A simple class to store in the array
public class Employee {
private int empID;

public Employee (int empID) {
this.empID = empID;

public override string ToString() {
return empID.ToString();

public class Tester {

// // method to take variable number of int parameters and dispaly
// public void DisplayVals(params int [] intArray) {
// foreach (int i in intArray)
// Console.WriteLine(i);
// }

// method to take variable number of object parameters and display
public void DisplayVals(params object [] objArray) {
foreach (object o in objArray)

public static void Main() {

Tester t = new Tester();

Console.WriteLine("Showing the variable number of integers");

Console.WriteLine("Passing an explicit array");
int [] intArray = {1,2,3,4,5,6};

Employee [] empArray = new Employee[3];
// populate the Array
for(int i=0; i<empArray.Length;i++)
empArray[i] = new Employee(i+5);
Console.WriteLine("Passing an Employee Array");

Nov 17 '05 #1
Share this Question
Share on Google+
1 Reply

P: n/a
The language spec says:

"Array covariance specifically does not extend to arrays of value-types. For
example, no conversion exists that permits an int[] to be treated as an

When you pass an int[], it gets loaded into an object[] of length 1 and
passed to your method.

I do not think there is an easy solution - you might be able to do what you
want with reflection.
Nov 17 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.