Rakesh Sawant
Rakesh Sawant

Reputation: 69

add multiple datatype using collection in c#

In one of the interview question i asked below question,i would like to ask you the same as i failed to answer and still not getting clear idea on it here is the code

public class Bike
{
    public Bike() { }

    public virtual string GetBikedetails()
    {
        return "This is General Bike";
    }
}

public class Honda : Bike
{
    public Honda() { }

    public override string GetBikedetails()
    {
        return "This is Honda Bike";
    }
}

public class Hero : Bike
{
    public Hero() { }

    public override string GetBikedetails()
    {
        return "This is Hero Bike";
    }
}

Now following question was asked with reference to above code 1.Make three instance of the class present 2.add them in a collection 3.iterate in a collection to get the object individually

Please respond with your answer.

Upvotes: 0

Views: 39

Answers (1)

Steve
Steve

Reputation: 216313

You have already everything in place. Need only to create a List of Bike and add the elements of the specific derived type.

List<Bike> myList = new List<Bike>();
Bike b = new Bike();
Honda h = new Honda();
Hero r = new Hero();
myList.Add(b);
myList.Add(h);
myList.Add(r);

foreach(var x in myList)
    Console.WriteLine(x.GetBikedetails());

Upvotes: 2

Related Questions