Different behaviour of method overloading in C#

Posted by Wondering on Stack Overflow See other posts from Stack Overflow or by Wondering
Published on 2010-05-12T18:21:40Z Indexed on 2010/05/12 18:24 UTC
Read the original article Hit count: 266

Filed under:

Hi All, I was going through C# Brainteasers(http://www.yoda.arachsys.com/csharp/teasers.html) and came accross one question:what should be the o/p of below code

class Base
 {
     public virtual void Foo(int x)
      {
    Console.WriteLine ("Base.Foo(int)");
        }
  }

   class Derived : Base
  {
public override void Foo(int x)
{
    Console.WriteLine ("Derived.Foo(int)");
}

public void Foo(object o)
{
    Console.WriteLine ("Derived.Foo(object)");
}

}

  class Test
{
static void Main()
{
    Derived d = new Derived();
    int i = 10;
    d.Foo(i);  // it prints ("Derived.Foo(object)"
}
} 

but if I change the code to

enter code here  class Derived 
{
    public  void Foo(int x)
    {
        Console.WriteLine("Derived.Foo(int)");
    }

    public void Foo(object o)
    {
        Console.WriteLine("Derived.Foo(object)");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Derived d = new Derived();
        int i = 10;
        d.Foo(i); // prints  Derived.Foo(int)");

        Console.ReadKey();
    }
} 

I want to why the o/p is getting changde when we are inheriting vs not inheriting , why method overloading is behaving differently in both the cases

© Stack Overflow or respective owner

Related posts about c#