0

I have the following classes:

class SearchEngine
{
    public virtual void Search()
    {
        Console.WriteLine("Base Class");
    }
}

class Google: SearchEngine
{
    public override void Search()
    {
        Console.WriteLine("Google Class");
    }
}

class Yahoo: SearchEngine
{
    public new void Search()
    {
        Console.WriteLine("new method in Yahoo Class");
    }
}

And I call them this way:

SearchEngine s1 = new SearchEngine();
SearchEngine s2 = new Google();
SearchEngine s3 = new Yahoo();

s1.Search();
s2.Search();
s3.Search();

And I get the following results:

Base Class
Google Class
Base Class

My question is how to access the Search() method from the Yahoo class? (And yes I know this is a bad idea to use the new keyword like this and I know this not overriding a class)

Tagc
  • 8,736
  • 7
  • 61
  • 114
Sina Hoseinkhani
  • 318
  • 4
  • 15
  • 4
    "And yes I know this is bad idea to use new keyword like this and I know this not overriding a class". Than why are you doing it anyway? The problem can´t be solved unless you either omit `new` or use `Google s1 = new Google();` or `Yahoo s2 = new Yahoo();` resp. The `new` keyword only works when casting your instance to the derived class. Convcerting it to the base-class leads to calling the base-method. – MakePeaceGreatAgain Aug 30 '17 at 14:00
  • The answer is "use `override` instead of `new` on `Yahoo.Search()`. The answer to "no, seriously, how do I do it wrong" is some kind of Lovecraftian nightmare like this: `public static void Search(SearchEngine eng) { if (eng is Yahoo) (eng as Yahoo).Search(); else eng.Search(); }` – 15ee8f99-57ff-4f92-890c-b56153 Aug 30 '17 at 14:05

1 Answers1

3

To do this you need to change:

SearchEngine s3 = new Yahoo();

to:

var s3 = new Yahoo();

or:

Yahoo s3 = new Yahoo();

Your new method is not 'accessible' from the base class. That is the whole point of new when specified on a method.

mjwills
  • 23,389
  • 6
  • 40
  • 63