Lithicas
Lithicas

Reputation: 4013

Array with instances of different classes?

I'm wondering if there is a way to access the different methods in the objects that I have in the code below?

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication8
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            _test[0] = new TallGuy() {Height = 74, Name = "Teddy Long"};
            _test[1] = new TallGuy() {Height = 64, Name = "Teddy Shorter"};
            _test[2] = new TallGuy() {Height = 54, Name = "Teddy Shortest"};
        }

        private readonly object[] _test = new object[3];

        private void button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < _test.Length; i++)
            {
                //_test[i].        I can't call any methods here...
            }
        }
    }
}

The reason behind me using the Object type instead of an array of one class is because I want to store different types of objects in an array. Midway through my testing though I noticed that I was unable to access the methods of the objects I had already stored in the array, hence why there is only one type of object in there.

Upvotes: 2

Views: 95

Answers (2)

Darren
Darren

Reputation: 70804

You are only dealing with TallGuy objects in your array so you could use:

TallGuy[] _test = new TallGuy[3];

Which would provide you access to the TallGuy properties.

If you are also dealing with other object types such as SmallGuy then you would be better off having a object hierarchy and then having a strongly typed list rather than using object.

For instance:

public abstract class Guy 
{
     abstract public int Height { get; set; }
}

public class TallGuy : Guy 
{
    public override int Height 
    {
        get { return 100; }
        set { } 
    }
}

public class ShortGuy : Guy 
{
    public override int Height 
    {
        get { return 10; }
        set { }
    } 
}

With this structure in place you could have a List<Guy> and then let Contravariance/Covariance take over.

List<Guy> people = new List<Guy>();
people.Add(new TallGuy());
people.Add(new ShortGuy());

An alternative approach is to cast the object to the type within the foreach

 var tallGuy = _test[i] as TallGuy;

And then check if the cast was successfully by checking if it is null:

if (tallGuy != null) {

}

(But you would not have a strongly typed list and could hit performance problems from boxing the objects and then casting back).

Upvotes: 2

Juan
Juan

Reputation: 3705

You can access the methods by checking the types and casting them:

var obj = _test[i] as TallGuy;
if (obj != null) Console.WriteLine("Height: {0}", obj.Height);

You can also use reflection.

However are the types of the objects related? Maybe you should consider creating a common interface o super class and define the array of objects of that type.

Upvotes: 4

Related Questions