Click here to Skip to main content
15,896,153 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have Below classes and using these classes can we create?

1. Any collection of objects
2. Using that object collection i can print all class Hello method.

C#
class First
{
    public virtual void Hello()
    {
        Console.Write("First \n");
    }
}
class Second : First
{
    public override void Hello()
    {
        Console.Write("Second \n");
    }
}
class Third : First
{
    public new void Hello()
    {
        Console.Write("Third \n");
    }
}
I tried like this but it is giving output as
First
Second
First
C#
static void Main(string[] args)
{
     List<First> lst = new List<First>();
     lst.Add(f);
     Second s = new Second();
     lst.Add(s);
     Third t = new Third();
     lst.Add(t);

     foreach (First obj in lst)
     {
         obj.Hello();
     }
     Console.ReadKey();
 }

But we need output as
First
Second
Third
Posted

1 solution

Your problem is that your forgot to override the method Hello in your Third class like in your Second class.

Now, in your Third class you are using new keyword and this will hide the inherited method from your base class. And it will work fine in the case of: t.Hello();

But in your code you are trying to use in the context of a list of objects (polymorphism) and the usage of override keyword is mandatory for polymorphism.
 
Share this answer
 
v2
Comments
girishmeena 1-Apr-14 3:41am    
Thanks Raul
Raul Iloc 1-Apr-14 3:42am    
Welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900