Paul Moldovan Paul Moldovan - 1 year ago 76
C# Question

C# array of different objects

I have 2 classes B and D. I have to create an array with 4 elements 2 of type B and 2 of type D. How do I do it?

B o1 = new B();
D o2 = new D();
B o3 = new B();
D o4 = new D();

The array should be something like this:

array[0] = o1; array[1] = o2; array[2] = o3; array[3] = o4;

Answer Source

If there is no common base class other than object, you just need:

object[] array = new object[4];
array[0] = o1;
// etc

Or in a single shot:

object[] array = { o1, o2, o3, o4 };

To use the members specific to B or D, you'd need to cast when you retrieved the values from the array, e.g.

B b = (B) array[0];

If B and D have common methods, you could declare those in an interface which both classes implemented, and change the type of the array:

IBD[] array = new IBD[4];
array[0] = o1;


IBD[] array = { o1, o2, o3, o4 };

Finally, to address this:

I am new to c#. I don't like it but I have to learn it. In PHP it's 10000 times easier;

I'm sure if I tried to use PHP I'd find the same experience in the exact opposite direction. Don't assume that C# is "worse" or "harder" than PHP - it's just different, and you're bound to find it harder to use a language you're not familiar with than your "comfort zone" language.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download