matthias_buehlmann
matthias_buehlmann

Reputation: 5091

C# hide method FOR baseclass

I wonder if something like this is possible in C#:

public class A
{
    public string Foo() { return "Foo"; }
}

public class B : A
{
    public string Bar() { return Foo(); }
}

public class C : B
{
    public new string B.Foo() { return "Bar"; } // Hide A.Foo in B
}

Main()
{
    C c = new C();
    Console.WriteLine(c.Bar()); // Want to get "Bar"
}

by public new string B.Foo() { return "Bar"; } I mean do something in C (without changing A or B) that has the equivalent result as if public new string Foo() { return "Bar"; } was implemented in B. So, hide a method FOR a base class OF a base further up the inheritance hierarchy.

Upvotes: 0

Views: 76

Answers (1)

David L
David L

Reputation: 33873

What you want is virtual, which allows you to override base behavior in the inheriting type.

public class A
{
    public virtual string Foo() { return "Foo"; }
}

public class B : A
{
    public virtual string Bar() { return Foo(); }
}

public class C : B
{
    public override string Foo() { return "Bar"; } // Hide A.Foo in B
}

This outputs "bar"

Upvotes: 1

Related Questions