C# Abstract Classes and Abstract Members

Description

A class declared as abstract can never be instantiated. Only its concrete subclasses can be instantiated.

Abstract classes are able to define abstract members. Abstract members are like virtual members without a default implementation.

That implementation must be provided by the subclass, unless that subclass is also declared abstract.

Syntax

To declare an abstract method, use this general form:

abstract type name(parameter-list);

Example


using System;/*from   ww  w.ja  va 2s  .  c om*/
abstract class Shape
{
    public abstract int GetArea();

}

class Rectangle : Shape
{
    public int width;
    public int height;

    public override int GetArea()
    {
        return width * height;
    }
}

class Program
{
    static void Main(string[] args)
    {

        Rectangle r = new Rectangle();
        r.width = 5;
        r.height = 6;
        Console.WriteLine(r.GetArea());

    }
}

The output:





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor