Skip to content
Amal Hashim
All posts
Snippet

C# Abstract Class

How to declare abstract classes and abstract members in C#, and how a derived class overrides them.

1 min read#.NET#C#

Abstract classes are declared with the abstract keyword.

csharp
abstract class Stream
{
    public abstract void Write(char ch);
    public void WriteString(string s)
    {
        foreach (char ch in s) Write(ch);
    }
}

class File : Stream
{
    public override void Write(char ch)
    {
        // write ch to disk
    }
}

Abstract methods have no body, so they have no implementation. They are implicitly virtual. Abstract classes cannot be instantiated.

Properties and indexers can be abstract too.

csharp
abstract class Enumerator
{
    public abstract void Add(object x);                // method
    public abstract string Name { get; }               // property
    public abstract object this[int i] { get; set; }   // indexer
}

class List : Enumerator
{
    public override void Add(object x) { /* ... */ }
    public override string Name { get { /* ... */ return null; } }
    public override object this[int i]
    {
        get { /* ... */ return null; }
        set { /* ... */ }
    }
}