Why we use virtual and override keywords in c#

Can anyone explain me what’s the point of overriding base class implementations (if its not abstract), because it’s not ethical move to modify features of the parent class according to the wishes of derived classes. The best way is to make the base classes abstract and carry on the inheritance chain. Whereas when designing a class hierarchy initially we gather or elicit all the essential requirements/features that should be belonged to a base class. Therefore, in a middle of a project we do not need to change base class implementations. According to my knowledge, base class implementation should be a constant. Thus, under this aspect, there’s no real use of “override” keyword in c#. If it’s not so please explain me with an example.

4

Many times you will have dependencies in sub-classes, or may have to implement things differently.

class BasicCarModel
{
    public virtual void Accelerate(double speed)
    {
         RotateFrontWheels(speed);
    }
}

class LuxuryCarModel : BasicCarModel
{
    public override void Accelerate(double speed)
    {
        RotateAllWheels(speed);
    }
}

There is nothing at all wrong with creating virtual methods in concrete classes and in some cases they are very useful. The difficulty is that many novice programmers violate the Liskov Substitution Principle when doing so. Remember that an overridden method should appear to do the same thing if used as a base method. It should not strengthen or weaken the preconditions of the base method.

In the example I gave, the difference between the base class and the derived class was in the mechanics of how the car accelerated, not in the values allowed for speed. It did not throw any exceptions that were not expected by a calling class.

This is a contrived example, but the principle is the same. Do use virtual and override when needed. Don’t violate the LSP.

Here’s a non-abstract class which does some processing, and a sub class which only does processing at certain times of day.

class Foo
{
    public virtual bool IsReadyToProcess()
    {
        return true;
    }
    public void Process()
    {
        if (!IsReadyToProcess()) throw new Exception("Not ready");
        else
          // Process
    }
}

class TimeboundFoo : Foo
{
    public TimeboundFoo(int hour) { Hour = hour; }

    public int Hour { get; private set; }

    public override bool IsReadyToProcess()
    {
       return DateTime.Now.Hour == Hour;
    }
}

Usage:

List<Foo> foos = new List<Foo>();
foos.Add(new Foo());
foos.Add(new TimeboundFoo(12));

foreach (var foo in foos)
{
   if (foo.IsReadyToProcess()) foo.Process();
}

At noon, it’ll process both Foo objects, but at any other hour it’ll only process the one.
It’s a very contrived example, but you can generalize from here.

Virtual/abstract methods and overriding are commonly used in. Template pattern.

The template pattern provides a way to define what you think would be a good general guideline for a class to follow, but you allow future implementers to be more specific, or even unique in their way of doing something.

1

How about a simple case where you MUST use override:

Any class that implements the IDisposable interface. (And any class that owns a resource that must be cleaned up should implement it.)

2

Note: The OP mention that it seems OK to you to override base implementations of abstract classes, so this answer is tailored around that assumption.

It’s probably a bad idea to inherit from classes which were not designed for inheritance (see why are concrete types rarely useful as bases for further derivation). Many of the C# experts believe that C# classes should be sealed by default.

See also Why Are So Many Of The Framework Classes Sealed?.

All that being said, the only difference between an abstract class and a concrete class that was designed for inheritance is that the latter can be instantiated. Alternatively, a concrete class is like an abstract class that has no methods lacking some form of default implementation. All of the design considerations that make it OK to inherit from an abstract class also make it OK to inherit from a concrete class that was designed for inheritance.

An interesting example is UserControl. Being able to derive from UserControl is of high value, since there is a lot of asp.net functionality which leverages polymorphism.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật