The abstract modifier can be used with classes, methods, properties, indexers, and events.
Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes.
Abstract classes have the following features:
Use the abstract modifier in a method or property declaration to indicate that the method or property does not contain implementation.
Abstract methods have the following features:
public abstract void MyMethod();
Abstract properties behave like abstract methods, except for the differences in declaration and invocation syntax.
An abstract class must provide implementation for all interface members.
An abstract class that implements an interface might map the interface methods onto abstract methods. For example:
interface I
{
void M();
}
abstract class C: I
{
public abstract void M();
}
For more information, see
In this example, the class MyDerivedC is derived from an abstract class MyBaseC. The abstract class contains an abstract method, MyMethod(), and two abstract properties, GetX() and GetY().
// abstract_keyword.cs
// Abstract Classes
using System;
abstract class MyBaseC // Abstract class
{
protected int x = 100;
protected int y = 150;
public abstract void MyMethod(); // Abstract method
public abstract int GetX // Abstract property
{
get;
}
public abstract int GetY // Abstract property
{
get;
}
}
class MyDerivedC: MyBaseC
{
public override void MyMethod()
{
x++;
y++;
}
public override int GetX // overriding property
{
get
{
return x+10;
}
}
public override int GetY // overriding property
{
get
{
return y+10;
}
}
public static void Main()
{
MyDerivedC mC = new MyDerivedC();
mC.MyMethod();
Console.WriteLine("x = {0}, y = {1}", mC.GetX, mC.GetY);
}
}
x = 111, y = 161
In the preceding example, if you attempt to instantiate the abstract class by using a statement like this:
MyBaseC mC1 = new MyBaseC(); // Error
you will get the following error message:
Cannot create an instance of the abstract class 'MyBaseC'.
virtual | override | C# Keywords | Modifiers |