In C# a method or class
can be marked as abstract
. An abstract
method has no implementation. Its implementation logic is provided instead by classes that derive from it.
We use an abstract
class
to create a base template for derived classes. With abstract
, we enforce a design rule at the level of the compiler.
We introduce an abstract
class
named Test. Two other classes derive from Test: the Example1
and Example2
classes. In the Test class
, we have a field, and an abstract
method.
class
like Example1
or Example2
, we must provide override
methods for all abstract
methods in the abstract
class
.A()
method in both derived classes satisfies this requirement.using System; abstract class Test { public int _a; public abstract void A(); } class Example1 : Test { public override void A() { Console.WriteLine("Example1.A"); base._a++; } } class Example2 : Test { public override void A() { Console.WriteLine("Example2.A"); base._a--; } } class Program { static void Main() { // Reference Example1 through Test type. Test test1 = new Example1(); test1.A(); // Reference Example2 through Test type. Test test2 = new Example2(); test2.A(); } }Example1.A Example2.A
abstract
memberWe must provide an "override
" method for abstract
methods. Here Example1
does not implement the "A" method and the compiler does not like this.
abstract class Test { public abstract void A(); } class Example1 : Test { } class Program { static void Main() { } }error CS0534: 'Example1' does not implement inherited abstract member 'Test.A()'
An abstract
class
can have an instance field in it. The derived classes can access this field through "base." This is a key difference between abstract
classes and interfaces.
The important part of an abstract
class
is that you can never use it separately from a derived class
. It can only be used through another class
.
What is the difference between an abstract
class
and an interface
? An abstract
class
can have fields on it. These fields can be referenced through the derived classes.
interface
cannot have fields. An abstract
class
is the same thing as an interface
except it is a class
, not just a contract.In my testing, abstract
classes with virtual
methods have better performance than interface
implementations in .NET. Abstract classes can help performance.
An abstract
class
is not directly instantiated—instead, derived classes must inherit from it. Compared to an interface
, it adds features and improves performance.