0

So this is what i'm trying to achieve, is there an elegant way to do this?

public class item
{
}

public class A : item
{
   public int a;
}

public class B : item
{
   public string b;
}

public class example
{
  A classA = new A();
  B classB = new B();

  item[] itemArray = {classA, classB}

  foreach(item i in itemArray)
  {
    // get int a if item i is ofType A
    // get string b if item i is ofType B 
  }
}

I've tried overriding but that forces me to create virtual fields of both a and b in the base class. There has to be a better way.

Lesser
  • 11
  • 3
  • Declare your ints public, then you can do `if (item is A itemA) { Console.WriteLine(itemA.a); } else if (item is B itemB) { Console.WriteLine(itemB.b); }` or by using a switch-case: `switch (item) { case A itemA: …; break; case B itemB: …; break; }`. Also it’s best practice to use properties instead of fields if they are public for a variety of reasons. – ckuri Dec 11 '20 at 21:28

2 Answers2

0

This would probably be the best way, I feel so silly for not thinking about simply casting it to the right class.

public class example
{
  A classA = new A();
  B classB = new B();

  item[] itemArray = {classA, classB}

  foreach(item i in itemArray)
  {
    if(i.GetType() == Type.GetType("A"))
    {
        A blabla = (A)i;
        Console.WriteLine(blabla.a);
    }
  }
}
Lesser
  • 11
  • 3
-1

Here's how this should be done:

void Main()
{
    A classA = new A() { a = 42 };
    B classB = new B() { b = "Foo" };

    Item[] itemArray = new Item[] { classA, classB };

    foreach (Item i in itemArray)
    {
        if (i is A i_as_A)
        {
            Console.WriteLine(i_as_A.a);
        }
        if (i is B i_as_B)
        {
            Console.WriteLine(i_as_B.b);
        }
    }
}

public class Item { }

public class A : Item
{
    public int a;
}

public class B : Item
{
    public string b;
}

If I run that I get:

42
Foo
Enigmativity
  • 113,464
  • 11
  • 89
  • 172