When would you use Abstract methods over virtual methods in C#? [duplicate] - c#

What is the difference between an abstract method and a virtual method? In which cases is it recommended to use abstract or virtual methods? Which one is the best approach?

An abstract function cannot have functionality. You're basically saying, any child class MUST give their own version of this method, however it's too general to even try to implement in the parent class.
A virtual function, is basically saying look, here's the functionality that may or may not be good enough for the child class. So if it is good enough, use this method, if not, then override me, and provide your own functionality.

An abstract function has no implemention and it can only be declared on an abstract class. This forces the derived class to provide an implementation.
A virtual function provides a default implementation and it can exist on either an abstract class or a non-abstract class.
So for example:
public abstract class myBase
{
//If you derive from this class you must implement this method. notice we have no method body here either
public abstract void YouMustImplement();
//If you derive from this class you can change the behavior but are not required to
public virtual void YouCanOverride()
{
}
}
public class MyBase
{
//This will not compile because you cannot have an abstract method in a non-abstract class
public abstract void YouMustImplement();
}

Only abstract classes can have abstract members.
A non-abstract class that inherits from an abstract class must override its abstract members.
An abstract member is implicitly virtual.
An abstract member cannot provide any implementation (abstract is called pure virtual in some languages).

You must always override an abstract function.
Thus:
Abstract functions - when the inheritor must provide its own implementation
Virtual - when it is up to the inheritor to decide

Abstract Function:
It can be declared only inside abstract class.
It contains only
method declaration not the implementation in abstract class.
It must be overridden in derived class.
Virtual Function:
It can be declared inside abstract as well as non abstract class.
It contains method implementation.
It may be overridden.

explanation: with analogies. hopefully it will help you.
Context
I work on the 21 st floor of a building. And I'm paranoid about fire. Every now and again, somewhere in the world, a fire is burning down a sky scraper. But luckily we have an instruction manual somewhere here on what to do in case of fire:
FireEscape()
Don't collect belongings
Walk to fire escape
Walk out of building
This is basically a virtual method called FireEscape()
Virtual Method
This plan is pretty good for 99% of the circumstances. It's a basic plan which works. But there is a 1% chance that the fire escape is blocked or damaged in which case you are completely screwed and you'll become toast unless you take some drastic action. With virtual methods you can do just that: you can override the basic FireEscape() plan with your own version of the plan:
Run to window
Jump out the window
Parachute safely to the bottom
In other words virtual methods provide a basic plan, which can be overriden if you need to. Subclasses can override the parent class' virtual method if the programmer deems it appropriate.
Abstract methods
Not all organisations are well drilled. Some organisations don't do fire drills. They don't have an overall escape policy. Every man is for himself. Management are only interested in such a policy existing.
In other words, each person is forced to develop his own FireEscape() method. One guy will walk out the fire escape. Another guy will parachute. Another guy will use rocket propulsion technology to fly away from the building. Another guy will abseil out. Management don't care how you escape, so long as you have a basic FireEscape() plan - if they don't you can be guaranteed OHS will come down on the organisation like a tonne of bricks. This is what is meant by an abstract method.
What's the difference between the two again?
Abstract method: sub classes are forced to implement their own FireEscape method. With a virtual method, you have a basic plan waiting for you, but can choose to implement your own if it's not good enough.
Now that wasn't so hard was it?

Abstract method:
When a class contains an abstract method, that class must be declared as abstract.
The abstract method has no implementation and thus, classes that derive from that abstract class, must provide an implementation for this abstract method.
Virtual method:
A class can have a virtual method. The virtual method has an implementation.
When you inherit from a class that has a virtual method, you can override the virtual method and provide additional logic, or replace the logic with your own implementation.
When to use what:
In some cases, you know that certain types should have a specific method, but, you don't know what implementation this method should have.
In such cases, you can create an interface which contains a method with this signature.
However, if you have such a case, but you know that implementors of that interface will also have another common method (for which you can already provide the implementation), you can create an abstract class.
This abstract class then contains the abstract method (which must be overriden), and another method which contains the 'common' logic.
A virtual method should be used if you have a class which can be used directly, but for which you want inheritors to be able to change certain behaviour, although it is not mandatory.

An abstract method is a method that must be implemented to make a concrete class. The declaration is in the abstract class (and any class with an abstract method must be an abstract class) and it must be implemented in a concrete class.
A virtual method is a method that can be overridden in a derived class using the override, replacing the behavior in the superclass. If you don't override, you get the original behavior. If you do, you always get the new behavior. This opposed to not virtual methods, that can not be overridden but can hide the original method. This is done using the new modifier.
See the following example:
public class BaseClass
{
public void SayHello()
{
Console.WriteLine("Hello");
}
public virtual void SayGoodbye()
{
Console.WriteLine("Goodbye");
}
public void HelloGoodbye()
{
this.SayHello();
this.SayGoodbye();
}
}
public class DerivedClass : BaseClass
{
public new void SayHello()
{
Console.WriteLine("Hi There");
}
public override void SayGoodbye()
{
Console.WriteLine("See you later");
}
}
When I instantiate DerivedClass and call SayHello, or SayGoodbye, I get "Hi There" and "See you later". If I call HelloGoodbye, I get "Hello" and "See you later". This is because SayGoodbye is virtual, and can be replaced by derived classes. SayHello is only hidden, so when I call that from my base class I get my original method.
Abstract methods are implicitly virtual. They define behavior that must be present, more like an interface does.

Abstract methods are always virtual. They cannot have an implementation.
That's the main difference.
Basically, you would use a virtual method if you have the 'default' implementation of it and want to allow descendants to change its behaviour.
With an abstract method, you force descendants to provide an implementation.

I made this simpler by making some improvements on the following classes (from other answers):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestOO
{
class Program
{
static void Main(string[] args)
{
BaseClass _base = new BaseClass();
Console.WriteLine("Calling virtual method directly");
_base.SayHello();
Console.WriteLine("Calling single method directly");
_base.SayGoodbye();
DerivedClass _derived = new DerivedClass();
Console.WriteLine("Calling new method from derived class");
_derived.SayHello();
Console.WriteLine("Calling overrided method from derived class");
_derived.SayGoodbye();
DerivedClass2 _derived2 = new DerivedClass2();
Console.WriteLine("Calling new method from derived2 class");
_derived2.SayHello();
Console.WriteLine("Calling overrided method from derived2 class");
_derived2.SayGoodbye();
Console.ReadLine();
}
}
public class BaseClass
{
public void SayHello()
{
Console.WriteLine("Hello\n");
}
public virtual void SayGoodbye()
{
Console.WriteLine("Goodbye\n");
}
public void HelloGoodbye()
{
this.SayHello();
this.SayGoodbye();
}
}
public abstract class AbstractClass
{
public void SayHello()
{
Console.WriteLine("Hello\n");
}
//public virtual void SayGoodbye()
//{
// Console.WriteLine("Goodbye\n");
//}
public abstract void SayGoodbye();
}
public class DerivedClass : BaseClass
{
public new void SayHello()
{
Console.WriteLine("Hi There");
}
public override void SayGoodbye()
{
Console.WriteLine("See you later");
}
}
public class DerivedClass2 : AbstractClass
{
public new void SayHello()
{
Console.WriteLine("Hi There");
}
// We should use the override keyword with abstract types
//public new void SayGoodbye()
//{
// Console.WriteLine("See you later2");
//}
public override void SayGoodbye()
{
Console.WriteLine("See you later");
}
}
}

Binding is the process of mapping a name to a unit of code.
Late binding means that we use the name, but defer the mapping. In other words, we create/mention the name first, and let some subsequent process handle the mapping of code to that name.
Now consider:
Compared to humans, machines are really good at searching and sorting
Compared to machines, humans are really good at invention and innovation
So, the short answer is: virtual is a late binding instruction for the machine (runtime) whereas abstract is the late binding instruction for the human (programmer)
In other words, virtual means:
“Dear runtime, bind the appropriate code to this name by doing what you do best: searching”
Whereas abstract means:
“Dear programmer, please bind the appropriate code to this name by doing what you do best: inventing”
For the sake of completeness, overloading means:
“Dear compiler, bind the appropriate code to this name by doing what you do best: sorting”.

You basically use a virtual method when you want the inheritors to extend the functionality IF they want to.
You use abstract methods when you want the inheritors to implement the functionality (and in this case they have no choice)

Virtual Method:
Virtual means we CAN override it.
Virtual Function has an implementation. When we inherit the class we
can override the virtual function and provide our own logic.
We can change the return type of Virtual function while implementing the
function in the child class(which can be said as a concept of
Shadowing).
Abstract Method
Abstract means we MUST override it.
An abstract function has no implementation and must be in an abstract class.
It can only be declared. This forces the derived class to provide the implementation of it.
An abstract member is implicitly virtual. The abstract can be called as pure virtual in some of the languages.
public abstract class BaseClass
{
protected abstract void xAbstractMethod();
public virtual void xVirtualMethod()
{
var x = 3 + 4;
}
}

I have seen in some places the abstract method is defined as below. **
"An Abstract Method must have to implement in the child class"
**
I felt it is like .
It is not necessary that an abstract method has to be implemented in a child class, if the child class is also abstract ..
1)An abstract method cant be a private method.
2)An Abstract method cant be implemented in the same abstract class.
I would say ..if we are implementing an abstract class, you must have to override the abstract methods from the base abstract class.
Because.. Implementing the abstract method is with override key word .Similar to Virtual method.
It is not necessary for a virtual method to be implemented in an inherited class.
----------CODE--------------
public abstract class BaseClass
{
public int MyProperty { get; set; }
protected abstract void MyAbstractMethod();
public virtual void MyVirtualMethod()
{
var x = 3 + 4;
}
}
public abstract class myClassA : BaseClass
{
public int MyProperty { get; set; }
//not necessary to implement an abstract method if the child class is also abstract.
protected override void MyAbstractMethod()
{
throw new NotImplementedException();
}
}
public class myClassB : BaseClass
{
public int MyProperty { get; set; }
//You must have to implement the abstract method since this class is not an abstract class.
protected override void MyAbstractMethod()
{
throw new NotImplementedException();
}
}

Most of the above examples use code - and they are very very good. I need not add to what they say, but the following is a simple explanation that makes use of analogies rather than code/technical terms.
Simple Explanation - Explanation using analogies
Abstract Method
Think George W Bush. He says to his soldiers: "Go fight in Iraq". And that's it. All he has specified is that fighting must be done. He does not specify how exactly that will happen. But I mean, you can't just go out and "fight": what does that mean exactly? do I fight with a B-52 or my derringer? Those specific details are left to someone else. This is an abstract method.
Virtual Method
David Petraeus is high up in the army. He has defined what fight means:
Find the enemy
Neutralise him.
Have a beer afterwards
The problem is that it is a very general method. It's a good method that works, but sometimes is not specific enough. Good thing for Petraeus is that his orders have leeway and scope - he has allowed others to change his definition of "fight", according to their particular requirements.
Private Job Bloggs reads Petraeus' order and is given permission to implement his own version of fight, according to his particular requirements:
Find enemy.
Shoot him in the head.
Go Home
Have beer.
Nouri al Maliki also receives the same orders from Petraeus. He is to fight also. But he is a politician, not an infantry man. Obviously he cannot go around shooting his politican enemies in the head. Because Petraeus has given him a virtual method, then Maliki can implement his own version of the fight method, according to his particular circumstances:
Find enemy.
Have him arrested with some BS trumped up charges.
Go Home
Have beer.
IN other words, a virtual method provides boilerplate instructions - but these are general instructions, which can be made more specific by people down the army heirarchy, according to their particular circumstances.
The difference between the two
George Bush does not prove any implementation details. This must be provided by someone else. This is an abstract method.
Petraeus on the other hand does provide implementation details but he has given permission for his subordinates to override his orders with their own version, if they can come up with something better.
hope that helps.

Abstract function(method) :
● An abstract method is a method which is declared with the keyword abstract.
● It does not have body.
● It should be implemented by the derived class.
● If a method is abstract then the class should abstract.
virtual function(method) :
● A virtual method is the method which is declared with the keyword virtual and it can be overridden by the derived class method by using override keyword.
● It's up to the derived class whether to override it or not.

The answer has been provided a number of times but the the question about when to use each is a design-time decision. I would see it as good practice to try to bundle common method definitions into distinct interfaces and pull them into classes at appropriate abstraction levels. Dumping a common set of abstract and virtual method definitions into a class renders the class unistantiable when it may be best to define a non-abstract class that implements a set of concise interfaces. As always, it depends on what best suits your applications specific needs.

Abstract function cannot have a body and MUST be overridden by child classes
Virtual Function will have a body and may or may not be overridden by child classes

From general object oriented view:
Regarding abstract method: When you put an abstract method in the parent class actually your are saying to the child classes: Hey note that you have a method signature like this. And if you wanna to use it you should implement your own!
Regarding virtual function: When you put a virtual method in the parent class you are saying to the derived classes : Hey there is a functionality here that do something for you. If this is useful for you just use it. If not, override this and implement your code, even you can use my implementation in your code !
this is some philosophy about different between this two concept in General OO

An abstract function is "just" a signature, without an implementation.
It is used in an interface to declare how the class can be used.
It must be implemented in one of the derived classes.
Virtual function (method actually), is a function you declare as well, and should implemented in one of the inheritance hierarchy classes.
The inherited instances of such class, inherit the implementation as well, unless you implement it, in a lower hierarchy class.

From a C++ background, C# virtual corresponds to C++ virtual, while C# abstract methods corresponds to C++ pure virtual function

If a class derives from this abstract class, it is then forced to override the abstract member. This is different from the virtual modifier, which specifies that the member may optionally be overridden.

There are nothing call virtual class in C#.
For functions
Abstract function only have signature only,the drive class should override with functionality.
Virtual function will hold the part of functionality the drive class may or may not override it according to the requirement
You can decide with your requirement.

Abstract method doesnt have an implementation.It is declared in the parent class. The child class is resposible for implementing that method.
Virtual method should have an implementation in the parent class and it facilitates the child class to make the choice whether to use that implementation of the parent class or to have a new implementation for itself for that method in child class.

An abstract function or method is a public "operation's name" exposed by a class, its aim, along with abstract classes, is primarily provide a form of constraint in objects design against the structure that an object have to implement.
In fact the classes that inherit from its abstract class have to give an implementation to this method, generally compilers raise errors when they don't.
Using abstract classes and methods is important mostly to avoid that by focusing on implementation details when designing classes, the classes structure be too related to the implementations, so creating dependences and coupling between classes that collaborate among them.
A virtual function or method is simply a method that models a public behaviour of a class, but that we can leave free to modify it in the inheritance chain, because we think that child classes could have need to implement some specific extensions for that behaviour.
They both represent a form of polymorpfhism in object orientation paradigm.
We can use abstract methods and virtual functions together to support a good inheritance model.
We design a good abstract structure of main objects of our solution, then create basic implementations by locating those more prone to further specializations and we make these ones as virtuals, finally we specialize our basic implementations, eventyually "overriding" inherited virtual ones.

Here I am writing some sample code hoping this may be a rather tangible example to see the behaviors of the interfaces, abstract classes and ordinary classes on a very basic level. You can also find this code in github as a project if you want to use it as a demo: https://github.com/usavas/JavaAbstractAndInterfaceDemo
public interface ExampleInterface {
// public void MethodBodyInInterfaceNotPossible(){
// }
void MethodInInterface();
}
public abstract class AbstractClass {
public abstract void AbstractMethod();
// public abstract void AbstractMethodWithBodyNotPossible(){
//
// };
//Standard Method CAN be declared in AbstractClass
public void StandardMethod(){
System.out.println("Standard Method in AbstractClass (super) runs");
}
}
public class ConcreteClass
extends AbstractClass
implements ExampleInterface{
//Abstract Method HAS TO be IMPLEMENTED in child class. Implemented by ConcreteClass
#Override
public void AbstractMethod() {
System.out.println("AbstractMethod overridden runs");
}
//Standard Method CAN be OVERRIDDEN.
#Override
public void StandardMethod() {
super.StandardMethod();
System.out.println("StandardMethod overridden in ConcreteClass runs");
}
public void ConcreteMethod(){
System.out.println("Concrete method runs");
}
//A method in interface HAS TO be IMPLEMENTED in implementer class.
#Override
public void MethodInInterface() {
System.out.println("MethodInInterface Implemented by ConcreteClass runs");
// Cannot declare abstract method in a concrete class
// public abstract void AbstractMethodDeclarationInConcreteClassNotPossible(){
//
// }
}
}

Figure. — Traditional threefold classification of propositions.
In deontic logic (the study of obligation and permission), every proposition is obligatory (‘must’ operator), optional (‘may and may not’ operator), or impermissible (‘must not’ operator), and no proposition falls into more than one of these three categories.
Furthermore, the permissible (‘may’ operator) propositions are those that are obligatory or optional, the omissible (‘may not’ operator) propositions are those that are impermissible or optional, and the non-optional (‘must or must not’ operator) propositions are those that are obligatory or impermissible.
In particular, an obligatory proposition is permissible, and an impermissible proposition is omissible.
Applying those operators to the proposition ’the method is overridden’ yields the following propositions:
abstract (pure)/concrete method: the method must be overridden/may not be overridden;
virtual/real (final) method: the method may be overridden/must not be overridden.
In particular, an abstract method is virtual, and a real method is concrete.

To my understanding:
Abstract Methods:
Only the abstract class can hold abstract methods. Also the derived class need to implement the method and no implementation is provided in the class.
Virtual Methods:
A class can declare these and also provide the implementation of the same. Also the derived class need to implement of the method to override it.

Related

C# language purpose of "override" abstract method [duplicate]

Just out of curiosity I tried overriding a abstract method in base class, and method the implementation abstract. As below:
public abstract class FirstAbstract
{
public abstract void SomeMethod();
}
public abstract class SecondAbstract : FirstAbstract
{
public abstract override void SomeMethod();
//?? what sense does this make? no implementaion would anyway force the derived classes to implement abstract method?
}
Curious to know why C# compiler allows writing 'abstract override'. Isn't it redundant? Should be a compile time error to do something like this. Does it serve to some use-case?
Thanks for your interest.
There's a useful example for this on Microsoft Docs - basically you can force a derived class to provide a new implementation for a method.
public class D
{
public virtual void DoWork(int i)
{
// Original implementation.
}
}
public abstract class E : D
{
public abstract override void DoWork(int i);
}
public class F : E
{
public override void DoWork(int i)
{
// New implementation.
}
}
If a virtual method is declared abstract, it is still virtual to any
class inheriting from the abstract class. A class inheriting an
abstract method cannot access the original implementation of the
method—in the previous example, DoWork on class F cannot call DoWork
on class D. In this way, an abstract class can force derived classes
to provide new method implementations for virtual methods.
I find it really useful for ensuring proper ToString() implementation in derived classes. Let's say you have abstract base class, and you really want all derived classes to define meanigful ToString() implementation because you are actively using it. You can do it very elegantly with abstract override:
public abstract class Base
{
public abstract override string ToString();
}
It is a clear signal to implementers that ToString() will be used in base class in some way (like writing output to user). Normally, they would not think about defining this override.
Interestingly enough, the Roslyn version of the C# compiler has an abstract override method in it, which I found odd enough to write an article about:
http://ericlippert.com/2011/02/07/strange-but-legal/
Imagine that SecondAbstract is in the middle of a three-class hierarchy, and it wants to implement some abstract methods from its base FirstAbstract while leaving some other method X to be implemented from its child ThirdAbstract.
In this case, SecondAbstract is forced to decorate the method X with abstract since it does not want to provide an implementation; at the same time, it is forced to decorate it with override since it is not defining a new method X, but wants to move the responsibility of implementing X to its child. Hence, abstract override.
In general, the concepts modelled by abstract and override are orthogonal. The first forces derived classes to implement a method, while the second recognizes that a method is the same as specified on a base class and not a new one.
Therefore:
neither keyword: "simple" method
abstract only: derived class must implement
override only: implementation of method defined in base class
abstract override: derived class must implement a method defined in base class
This is done because in child class you can not have abstract method with same name as in base class. override tells compiler that you are overriding the behavior of base class.
Hope this is what you are looking for.
If you did not declare SomeMethod as abstract override in SecondAbstract, the compiler would expect that class to contain an implementation of the method. With abstract override it is clear that the implementation should be in a class derived from SecondAbstract and not in SecondAbstract itself.
Hope this helps...
This design pattern is known as the Template Method pattern.
Wikipedia page on Template Methods
A simple, non-software example: There are a bunch of military units: tanks, jets, soldiers, battleships, etc. They all need to implement some common methods but they will implement them very differently:
Move()
Attack()
Retreat()
Rest()
etc...

Why is it required to have override keyword in front of abstract methods when we implement them in a child class?

When we create a class that inherits from an abstract class and when we implement the inherited abstract class why do we have to use the override keyword?
public abstract class Person
{
public Person()
{
}
protected virtual void Greet()
{
// code
}
protected abstract void SayHello();
}
public class Employee : Person
{
protected override void SayHello() // Why is override keyword necessary here?
{
throw new NotImplementedException();
}
protected override void Greet()
{
base.Greet();
}
}
Since the method is declared abstract in its parent class it doesn't have any implementation in the parent class, so why is the keyword override necessary here?
When we create a class that inherits from an abstract class and when we implement the inherited abstract class why do we have to use the override keyword?
"Why?" questions like this can be hard to answer because they are vague. I'm going to assume that your question is "what arguments could be made during language design to argue for the position that the override keyword is required?"
Let's start by taking a step back. In some languages, say, Java, methods are virtual by default and overridden automatically. The designers of C# were aware of this and considered it to be a minor flaw in Java. C# is not "Java with the stupid parts taken out" as some have said, but the designers of C# were keen to learn from the problematic design points of C, C++ and Java, and not replicate them in C#.
The C# designers considered overriding to be a possible source of bugs; after all, it is a way to change the behaviour of existing, tested code, and that is dangerous. Overriding is not something that should be done casually or by accident; it should be designed by someone thinking hard about it. That's why methods are not virtual by default, and why you are required to say that you are overriding a method.
That's the basic reasoning. We can now go into some more advanced reasoning.
StriplingWarrior's answer gives a good first cut at making a more advanced argument. The author of the derived class may be uninformed about the base class, may be intending to make a new method, and we should not allow the user to override by mistake.
Though this point is reasonable, there are a number of counterarguments, such as:
The author of a derived class has a responsibility to know everything about the base class! They are re-using that code, and they should do the due diligence to understand that code thoroughly before re-using it.
In your particular scenario the virtual method is abstract; it would be an error to not override it, and so it is unlikely that the author would be creating an implementation by accident.
Let's then make an even more advanced argument on this point. Under what circumstances can the author of a derived class be excused for not knowing what the base class does? Well, consider this scenario:
The base class author makes an abstract base class B.
The derived class author, on a different team, makes a derived class D with method M.
The base class author realizes that teams which extend base class B will always need to supply a method M, so the base class author adds abstract method M.
When class D is recompiled, what happens?
What we want to happen is the author of D is informed that something relevant has changed. The relevant thing that has changed is that M is now a requirement and that their implementation must be overloaded. D.M might need to change its behaviour once we know that it could be called from the base class. The correct thing to do is not to silently say "oh, D.M exists and extends B.M". The correct thing for the compiler to do is fail, and say "hey, author of D, check out this assumption of yours which is no longer valid and fix your code if necessary".
In your example, suppose the override was optional on SayHello because it is overriding an abstract method. There are two possibilities: (1) the author of the code intends to override an abstract method, or (2) the overriding method is overriding by accident because someone else changed the base class, and the code is now wrong in some subtle way. We cannot tell these possibilities apart if override is optional.
But if override is required then we can tell apart three scenarios. If there is a possible mistake in the code then override is missing. If it is intentionally overriding then override is present. And if it is intentionally not overriding then new is present. C#'s design enables us to make these subtle distinctions.
Remember compiler error reporting requires reading the mind of the developer; the compiler must deduce from wrong code what correct code the author likely had in mind, and give an error that points them in the correct direction. The more clues we can make the developer leave in the code about what they were thinking, the better a job the compiler can do in reporting errors and therefore the faster you can find and fix your bugs.
But more generally, C# was designed for a world in which code changes. A great many features of C# which appear "odd" are in fact there because they inform the developer when an assumption that used to be valid has become invalid because a base class changed. This class of bugs is called "brittle base class failures", and C# has a number of interesting mitigations for this failure class.
It's to specify whether you're trying to override another method in the parent class or create a new implementation unique to this level of the class hierarchy. It's conceivable that a programmer might not be aware of the existence of a method in a parent class with exactly the same signature as the one they create in their class, which could lead to some nasty surprises.
While it's true that an abstract method must be overridden in a non-abstract child class, the crafters of C# probably felt it's still better to be explicit about what you're trying to do.
Because abstract method is a virtual method with no implementation, per C# language specification, means that abstract method is implicitly a virtual method. And override is used to extend or modify the abstract or virtual implementation, as you can see here
To rephrase it a little bit - you use virtual methods to implement some kind of late binding, whereas abstract methods force the subclasses of the type to have the method explicitly overridden. That's the point, when method is virtual, it can be overridden, when it's an abstract - it must be overriden
To add to #StriplingWarrior's answer, I think it was also done to have a syntax that is consistent with overriding a virtual method in the base class.
public abstract class MyBase
{
public virtual void MyVirtualMethod() { }
public virtual void MyOtherVirtualMethod() { }
public abstract void MyAbtractMethod();
}
public class MyDerived : MyBase
{
// When overriding a virtual method in MyBase, we use the override keyword.
public override void MyVirtualMethod() { }
// If we want to hide the virtual method in MyBase, we use the new keyword.
public new void MyOtherVirtualMethod() { }
// Because MyAbtractMethod is abstract in MyBase, we have to override it:
// we can't hide it with new.
// For consistency with overriding a virtual method, we also use the override keyword.
public override void MyAbtractMethod() { }
}
So C# could have been designed so that you did not need the override keyword for overriding abstract methods, but I think the designers decided that would be confusing as it would not be consistent with overriding a virtual method.

What is the use of 'abstract override' in C#?

Just out of curiosity I tried overriding a abstract method in base class, and method the implementation abstract. As below:
public abstract class FirstAbstract
{
public abstract void SomeMethod();
}
public abstract class SecondAbstract : FirstAbstract
{
public abstract override void SomeMethod();
//?? what sense does this make? no implementaion would anyway force the derived classes to implement abstract method?
}
Curious to know why C# compiler allows writing 'abstract override'. Isn't it redundant? Should be a compile time error to do something like this. Does it serve to some use-case?
Thanks for your interest.
There's a useful example for this on Microsoft Docs - basically you can force a derived class to provide a new implementation for a method.
public class D
{
public virtual void DoWork(int i)
{
// Original implementation.
}
}
public abstract class E : D
{
public abstract override void DoWork(int i);
}
public class F : E
{
public override void DoWork(int i)
{
// New implementation.
}
}
If a virtual method is declared abstract, it is still virtual to any
class inheriting from the abstract class. A class inheriting an
abstract method cannot access the original implementation of the
method—in the previous example, DoWork on class F cannot call DoWork
on class D. In this way, an abstract class can force derived classes
to provide new method implementations for virtual methods.
I find it really useful for ensuring proper ToString() implementation in derived classes. Let's say you have abstract base class, and you really want all derived classes to define meanigful ToString() implementation because you are actively using it. You can do it very elegantly with abstract override:
public abstract class Base
{
public abstract override string ToString();
}
It is a clear signal to implementers that ToString() will be used in base class in some way (like writing output to user). Normally, they would not think about defining this override.
Interestingly enough, the Roslyn version of the C# compiler has an abstract override method in it, which I found odd enough to write an article about:
http://ericlippert.com/2011/02/07/strange-but-legal/
Imagine that SecondAbstract is in the middle of a three-class hierarchy, and it wants to implement some abstract methods from its base FirstAbstract while leaving some other method X to be implemented from its child ThirdAbstract.
In this case, SecondAbstract is forced to decorate the method X with abstract since it does not want to provide an implementation; at the same time, it is forced to decorate it with override since it is not defining a new method X, but wants to move the responsibility of implementing X to its child. Hence, abstract override.
In general, the concepts modelled by abstract and override are orthogonal. The first forces derived classes to implement a method, while the second recognizes that a method is the same as specified on a base class and not a new one.
Therefore:
neither keyword: "simple" method
abstract only: derived class must implement
override only: implementation of method defined in base class
abstract override: derived class must implement a method defined in base class
This is done because in child class you can not have abstract method with same name as in base class. override tells compiler that you are overriding the behavior of base class.
Hope this is what you are looking for.
If you did not declare SomeMethod as abstract override in SecondAbstract, the compiler would expect that class to contain an implementation of the method. With abstract override it is clear that the implementation should be in a class derived from SecondAbstract and not in SecondAbstract itself.
Hope this helps...
This design pattern is known as the Template Method pattern.
Wikipedia page on Template Methods
A simple, non-software example: There are a bunch of military units: tanks, jets, soldiers, battleships, etc. They all need to implement some common methods but they will implement them very differently:
Move()
Attack()
Retreat()
Rest()
etc...

Virtual methods without body

I was looking at some code in an abstract class:
public virtual void CountX(){}
public virtual void DoCalculation() { ...code}
Why should I declare an empty virtual method in an abstract class if it is not mandatory to override it in derived types?
Because if the default behaviour is to do nothing, but derived classes might want to do something. It's a perfectly valid structure.
It allows your base code to call it. You tend to see similar designs when there is "BeforeXXX" and "AfterXXX" code, at the base class this code is empty, but the method needs to be there to compile. In derived classes, this code is optional, but needs to be virtual to be overridden.
The fact that it is in an abstract class shouldn't confuse its behaviour.
An example:
abstract class Base
{
public void ProcessMessages(IMessage[] messages)
{
PreProcess(messages);
// Process.
PostProcess(messages);
}
public virtual void PreProcess(IMessage[] messages)
{
// Base class does nothing.
}
public virtual void PostProcess(IMessage[] messages)
{
// Base class does nothing.
}
}
class Derived : Base
{
public override void PostProcess(IMessage[] messages)
{
// Do something, log or whatever.
}
// Don't want to bother with pre-process.
}
If these methods (Pre, Post) were abstract, then all derived classes would need to implement them (likely as empty methods) - code litter that can be removed using empty virtual methods at the base.
As #Adam told you, there are many cases in which it makes sense. When you create an abstract class, it's because you want to create a common interface for all classes deriving from that one; however, at that level of inheritance you won't have enough information to be able to create working code for that method.
For example, if you create the class Figure, with the getArea() method, you won't be able to write code that is going to correctly calculate the area for all figures. You'll have to wait to write the code for Rectangle, or Circle (both deriving from Figure), in order to be able to write working code for them.
If it is MANDATORY to override and no default logics could be written in base class, than virtuality is wrong and method should be abstract. If the default action is to do nothing, than as Adam mentioned, making empty virtual method in base class is perfectly valid structure
When you declare the method as abstract, the inherited class has to override that method (provide an implementation). It is mandatory.
When the method is declared as virtual, the inheritor can override the method and provide an implementation other than the default.
From a design perspective this smells bad and indicates that the implementation of the design is in an immature state. If a method is not required by every class that derives a particular base class then by definition it does not belong in the base class. You will usually discover that this method is used by particular derivations of the base class and that indicates a new interface or layer of abstraction in your inheritance hierarchy.

Why does C# allow for an abstract class with no abstract members?

The C# spec, section 10.1.1.1, states:
An abstract class is permitted (but
not required) to contain abstract
members.
This allows me to create classes like this:
public abstract class A
{
public void Main()
{
// it's full of logic!
}
}
Or even better:
public abstract class A
{
public virtual void Main() { }
}
public abstract class B : A
{
public override sealed void Main()
{
// it's full of logic!
}
}
This is really a concrete class; it's only abstract in so far as one can't instantiate it. For example, if I wanted to execute the logic in B.Main() I would have to first get an instance of B, which is impossible.
If inheritors don't actually have to provide implementation, then why call it abstract?
Put another way, why does C# allow an abstract class with only concrete members?
I should mention that I am already familiar with the intended functionality of abstract types and members.
Perhaps a good example is a common base class that provides shared properties and perhaps other members for derived classes, but does not represent a concrete object. For example:
public abstract class Pet
{
public string Name{get;set;}
}
public class Dog : Pet
{
public void Bark(){ ... }
}
All pets have names, but a pet itself is an abstract concept. An instance of a pet must be a dog or some other kind of animal.
The difference here is that instead of providing a method that should be overridden by implementors, the base class declares that all pets are composed of at least a Name property.
The idea is to force the implementor to derive from the class as it is intended to provide only a basis for a presumably more specialized implementation. So the base class, while not having any abstract members may only contain core methods an properties that can be used as a basis for extension.
For example:
public abstract class FourLeggedAnimal
{
public void Walk()
{
// most 4 legged animals walk the same (silly example, but it works)
}
public void Chew()
{
}
}
public class Dog : FourLeggedAnimal
{
public void Bark()
{
}
}
public class Cat : FourLeggedAnimal
{
public void Purr()
{
}
}
I think a slightly more accurate representation of your question would be: Why does C# allow an abstract class with only concrete members?
The answer: There's no good reason not to. Perhaps someone out there has some organizational structure where they like to have a noninstantiatable class at the top, even if a class below it just inherits and adds nothing. There's no good reason not to support that.
You said it -- because you can't instantiate it; it is meant to be a template only.
It is not "really a concrete class" if you declare it as abstract. That is available to you as a design choice.
That design choice may have to do with creating entities that are (at risk of mixing the terminology) abstractions of real-world objects, and with readability. You may want to declare parameters of type Car, but don't want objects to be declarable as Car -- you want every object of type Car to be instantiated as a Truck, Sedan, Coupe, or Roadster. The fact that Car doesn't require inheritors to add implementation does not detract from its value as an abstract version of its inheritors that cannot itself be instantiated.
Abstract means providing an abstraction of behaviour. For example Vehicle is an abstract form. It doesn't have any real world instance, but we can say that Vehicle has accelerating behaviour. More specifically Ford Ikon is a vehicle, and Yamaha FZ is a vehicle. Both these have accelerating behaviour.
If you now make this in the class form. Vehicle is abstract class with Acceleration method. While you may/ may not provide any abstract method. But the business need is that Vehicle should not be instantiated. Hence you make it abstract. The other two classes - Ikon and FZ are concrete classes deriving from Vehicle class. These two will have their own properties and behaviours.
With regards to usage, using abstract on a class declaration but having no abstract members is the same as having the class public but using protected on its constructors. Both force the class to be derived in order for it to be instantiated.
However, as far as self-documenting code goes, by marking the class abstract it informs others that this class is never meant to be instantiated on its own, even if it has no virtual or abstract members. Whereas protecting the constructors makes no such assertion.
The compiler does not prevent implementation-logic, but in your case I would simply omit abstract ?! BTW some methods could be implemented with { throw Exception("must inherit"); } and the compiler could not distinguish fully implemented classes and functions including only throw.
Here's a potential reason:
Layer Supertype
It's not uncommon for all the objects
in a layer to have methods you don't
want to have duplicated throughout the
system. You can move all of this
behavior into a common Layer
Supertype.
-- Martin Fowler
There's no reason to prevent having only concrete methods in an abstract class - it's just less common. The Layer Supertype is a case where this might make sense.
I see abstract classes serving two main purposes:
An incomplete class that must be specialized to provide some concrete service. Here, abstract members would be optional. The class would provide some services that the child classes can use and could define abstract members that it uses to provide its service, like in the Template Method Pattern. This type of abstract class is meant to create an inheritance hierarchy.
A class that only provides static utility methods. In this case, abstract members don't make sense at all. C# supports this notion with static classes, they are implicitly abstract and sealed. This can also be achieved with a sealed class with a private constructor.

Categories

Resources