Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling derived methods on a baseclass collection

I have one abstract class named A, and other classes (B, C, D, E, ...) that implements A. My derived classes are holding values of different types. I also have a list of A objects.

    abstract class A { }
    class B : class A
    {
      public int val {get;private set;}
    }
    class C : class A
    {
      public double val {get;private set;}
    }
    class D : class A
    {
      public string val {get;private set;}
    }

    class Program
    {
        static void Main(string[] args)
        {
          List list = new List { new B(), new C(), new D(), new E() };
          // ... 

          foreach (A item in list)
          {
            Console.WriteLine(String.Format("Value is: {0}", item.val);
          }
        }
    }

...where the .val is not known by the base-class ofc.

How can i get this dynamic behaviour? I don't want to use getType in a long switch/if-statements.

like image 499
Omicron Avatar asked Feb 13 '14 06:02

Omicron


People also ask

How do you call a derived class function?

A virtual function is a member function of a base class that is overridden by a derived class. When you use a pointer or a reference to the base class to refer to a derived class object, you can call a virtual function for that object and have it run the derived class's version of the function.

Can we call derived class method from base class?

Even though the derived class can't call it in the base class, the base class can call it which effectively calls down to the (appropriate) derived class. And that's what the Template Method pattern is all about.

How do you call a derived class in C#?

The correct way is to add a method DoSomeMagic() in the base class, with default implementation, or abstract. The derived class should than override it to do its magic.

How do you call a derived class in Java?

A derived Java class can call a constructor in its base class using the super keyword. In fact, a constructor in the derived class must call the super's constructor unless default constructors are in place for both classes.


1 Answers

If you just want to get the string representation of val i recoment overriding ToString in each of the sub classes

public override string ToString()
{
    return val.ToString();
}

either way if you want the data in a sub class you need to represent it in the base class as some type they all have in common (like object). and you could do it like this

abstract class A 
{
    public abstract object GetValue();
}
class B : class A
{
    public int val {get;private set;}
    public override object GetValue()
    {
        return val;
    }
}
like image 99
Imapler Avatar answered Sep 30 '22 01:09

Imapler