0

Lets consider I have Class B and C which is inherited from class B:

namespace ConsoleApp1
{
 class B
 {
    public void foo(B obj)
    {
        Console.WriteLine("B1 ");
    }

    public void foo(C obj)
    {
        Console.WriteLine("B1 ");
    }
 }

 class C : B
 {
    public void foo(B obj)
    {
        Console.WriteLine("C1 ");
    }

    public void foo(C obj)
    {
        Console.WriteLine("C1 ");
    }
 }
 public class Program
 {

    static void Main(string[] args)
    {
        B c = new C();
        B b = new B();

        b.foo(c);
        c.foo(b);
        c.foo(c);

        Console.ReadLine();
    }
 }
}

I am getting these results:

B1

B1

B1

I don't understand what happened exactly specially for the part:

c.foo(b); // prints B1

c.foo(c); // prints B1

Note: this question is just a mirror of the java version which prints:

B1

C1

C1

It will be great if someone can explain why C# print different values than Java for exactly same OOP code!

Ant P
  • 24,820
  • 5
  • 68
  • 105
user2266175
  • 131
  • 2
  • 2
  • 7

2 Answers2

0

Your compiler warnings should tell you enough. It tells you your C.foo hides the method B.foo since you are not using inheritance. Instead of you are just overwriting a previous method declaration.

You should use virtual and override in C# to declare method inheritance.

class B
{
    public virtual void foo(B obj)
    {
        Console.WriteLine("B1 ");
    }

    public virtual void foo(C obj)
    {
        Console.WriteLine("B1 ");
    }
}

class C : B
{
    public override void foo(B obj)
    {
        Console.WriteLine("C1 ");
    }

    public override void foo(C obj)
    {
        Console.WriteLine("C1 ");
    }
}
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
-1

Look at your debug console, you will see:

warning CS0108: 'C.foo(B)' hides inherited member 'B.foo(B)'. Use the new keyword if hiding was intended.
warning CS0108: 'C.foo(C)' hides inherited member 'B.foo(C)'. Use the new keyword if hiding was intended.

If you want to know more, read Inheritance and Derived Classes (C# vs Java)

aloisdg
  • 22,270
  • 6
  • 85
  • 105