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)
Console.WriteLine(o.ToString());
}
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};
t.DisplayVals(intArray);
3. an user defined type, Employee which has overriden ToString()
method.
eg. Employee [] empArray = new Employee[3];
then created the employee objects with for loop and,
t.DisplayVals(empArray);
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
them
// public void DisplayVals(params int [] intArray) {
// foreach (int i in intArray)
// Console.WriteLine(i);
// }
// method to take variable number of object parameters and display
them
public void DisplayVals(params object [] objArray) {
foreach (object o in objArray)
Console.WriteLine(o.ToString());
}
public static void Main() {
Tester t = new Tester();
Console.WriteLine("Showing the variable number of integers");
t.DisplayVals(2,3,4,5);
Console.WriteLine("Passing an explicit array");
int [] intArray = {1,2,3,4,5,6};
t.DisplayVals(intArray);
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");
t.DisplayVals(empArray);
}
}