This question already has an answer here:
I have 2 classes
public class A
{
public A(string N)
{
Name = N;
}
public string Name { get; set; }
public void GetName()
{
Console.Write(Name);
}
}
public class B : A
{
public B(string N) : base(N)
{
}
public new void GetName()
{
Console.Write(new string(Name.Reverse().ToArray()));
}
}
I create a new object B which I want to call GetName from A and GetName from B
B foo = new B("foo");
foo.GetName(); // output "oof"
Expected Output "foooof"
I already tried public new void GetName() : base but that does not compile
To get your desired output you need to call the base GetName() method in the GetName() method of the Class B. Like this for example:
public class A
{
public A(string N)
{
Name = N;
}
public string Name { get; set; }
public void GetName()
{
Console.Write(Name);
}
}
public class B : A
{
public B(string N) : base(N)
{
}
public new void GetName()
{
base.GetName();
Console.Write(new string(Name.Reverse().ToArray()));
}
}
This will out put foooof
Use override and call the base class' method from the overridden method:
public class A
{
public virtual void GetName()
{
Console.Write(Name);
}
}
public class B : A
{
public override void GetName()
{
base.GetName();
Console.Write(new string(Name.Reverse().ToArray()));
}
}
The virtual keyword is used to modify a method and allow for it to be overridden in a derived class whereas the new modifier hides the base class method. By calling the base.GetName(); you are executing the base method BTW, this is why it has no difference that you use the new or override keywords here although I recommend that use override.
References:
Knowing When to Use Override and New Keywords
public class A
{
public A(string N)
{
Name = N;
}
public string Name { get; set; }
public virtual void GetName()
{
Console.Write(Name);
}
}
public class B : A
{
public B(string N) : base(N)
{
}
public override void GetName()
{
base.GetName();
Console.Write(new string(Name.Reverse().ToArray()));
}
}
Use override or new according to your choice. Like to handle these scenarios.
A foo = new B("foo");
foo.GetName();
or
A foo = new A("foo");
foo.GetName();
or
B foo = new B("foo");
foo.GetName();
this msdn link will give you clear picture.
base.GetName();seems to work withoutoverridetoo - ToshiGetName's result like mentioned in the code above. - S.Akbaribase.GetName();you are executing the base method BTW this is why it has no difference that you useneworoverridehere. But you should know that withnewyou hided the base method but with override you extended it. - S.Akbarinewis dangerous. Don't use it if you don't know what you are doing. - Patrick Hofman