Answer the question
In order to leave comments, you need to log in
Why use override, new to override, hide?
Good afternoon, it's not very clear why to use overriding / hiding when access to the base method is not needed, why not just override the method?
example:
class A
{
public string GetInt()
{
// бла бла бла
return 10;
}
}
class B : A
{
public string GetInt() // много мест,
{
// бла бла бла, но нет вызова метода из базового класса
return 20;
}
}
class Clock
{
public int Hours { get; set; }
public int Minutes { get; set; }
public int Seconds { get; set; }
public override string ToString() // переопределяем ToString из System.Object
{
return $"{Hours}:{Minutes}:{Seconds}";
}
}
Answer the question
In order to leave comments, you need to log in
It's not really about using a method from a base class.
The bottom line is that the overridden method will work if the class is cast to the base class A,
and the overridden method will only work in a specific class B.
new
class A { public string GetInt() => "10"; }
class B : A {public new string GetInt() => "20";}
B item= new B();
item.GetInt(); // вернет 20
A item2 = (A)item;
item.GetInt(); // вернет 10
class A { public virtual string GetInt() => "10"; }
class B : A {public override string GetInt() => "20";}
B item= new B();
item.GetInt(); // вернет 20
A item2 = (A)item;
item.GetInt(); // вернет 20
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question