Nickel_Chrome Nickel_Chrome - 2 months ago 5
C# Question

Update an inherited method C#

Pretty new guy here, starting to look deeper onto C#.

I was wondering if you can "update" an inherited method. Here in my example the "Mage" class inherits from "Hero". Both have a "Shout" method, yet the Mage shout should add a line of text to the screen, but I only get the Hero's one.

I don't want to override Hero's Shout, but "update it" so Hero's childrens can shout something else. I was expecting new to let me modify the old methods while still using it, but no luck. What am I missing?

public class Hero
{
protected string _name;

public string Name
{
get { return _name; }
set { _name = value; }
}

public Hero(string n)
{
Name = n;
}

public virtual void Shout()
{
Console.WriteLine("I am {0} and I am a hero! ", Name);
}
}

public class Mage : Hero
{
public Mage(string n) : base(n)
{
Name = n;
}

public new void Shout()
{
base.Shout();
// Next line does not print...
Console.WriteLine("Also, I am a fierce Mage!");
}
}


Tanks for any help, tip,...!

Main could be:

class Program
{
static void Main(string[] args)
{
var h = new Hero("Paul One-Eye");
// Old line, not working
// var m = new Hero("Zangdar the Just");
var m = new Mage("Zangdar the Just");

h.Shout();
m.Shout();
}
}


Expected output should be :


I am Paul One-Eye and I am a hero!

I am Zangdar the Just and I am a hero!

Also, I am a fierce Mage!


EDIT:
Overriding the method like this DOES change SOMETHING:

public override void Shout()
{
base.Shout();
Console.WriteLine("I am a fierce Mage!");
}

Answer

Your code is working fine But you initialized your Mage with the Base Hero class

You did

var h = new Hero("Paul One-Eye");
var m = new Hero("Zangdar the Just");

It should be

var h = new Hero("Paul One-Eye");
var m = new Mage("Zangdar the Just");
Comments