Object Oriented interview question

In past i being asked a lot in different variation of this same question :

public class SaladIngridient
{
}

public class FruitSaladSaladIngridient : SaladIngridient
{
}
    public class Salad
    {
        public virtual void WhatSaladAreYou(SaladIngridient ingridient)
        {
            Console.WriteLine("Salad with with {0}", ingridient);
        }
    }

    public class FruitSalad: Salad
    {
        public override void WhatSaladAreYou(SaladIngridient ingridient)
        {
            Console.WriteLine("Fruit salat with {0}", ingridient);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Test();
        }

What is the output ?

        static void Test()
        {
            SaladIngridient lead = new SaladIngridient();

            Salad baseSalad = new Salad();
            Salad fruitSalad = new Salad();

            SaladIngridient derivedLead = new FruitSaladSaladIngridient();

            Console.ForegroundColor = ConsoleColor.DarkRed;
            Console.WriteLine("Test - Base salad with different ingredients");
            Console.WriteLine("");

            baseSalad.WhatSaladAreYou(lead);
            baseSalad.WhatSaladAreYou(derivedLead);

            Console.WriteLine("---------------------------------------------");

            Console.WriteLine("Test - Fruit salad with different ingredients");
            Console.WriteLine("");

            fruitSalad.WhatSaladAreYou(lead);
            fruitSalad.WhatSaladAreYou(derivedLead);

            Console.WriteLine("---------------------------------------------");
            Console.WriteLine("");
        }

The output:

Salad with with DynamicExample.SaladIngridient
Salad with with DynamicExample.FruitSaladSaladIngridient
---------------------------------------------
Test - Fruit salad with different ingridients

Salad with with DynamicExample.SaladIngridient
Salad with with DynamicExample.FruitSaladSaladIngridient
---------------------------------------------

If you answer is different from this, one or/and you want to understand how is it working, this post will provide explanations.

Leave a Reply

Your email address will not be published. Required fields are marked *