S
S
Student Hard Worker2021-07-17 09:35:54
.NET
Student Hard Worker, 2021-07-17 09:35:54

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;
    }
}

in many places in such places they use override, new, I don’t understand why?

Example with metanit

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

1 answer(s)
I
Ilya, 2021-07-17
@EugeneTypescript

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

override
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 question

Ask a Question

731 491 924 answers to any question