Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit focus mode

abstract (C# Reference)

  • 2025-01-16
Feedback

In this article

Theabstract modifier indicates that the thing being modified has a missing or incomplete implementation. The abstract modifier can be used with classes, methods, properties, indexers, and events. Use theabstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes, not instantiated on its own. Members marked as abstract must be implemented by non-abstract classes that derive from the abstract class.

Example 1

In this example, the classSquare must provide an implementation ofGetArea because it derives fromShape:

abstract class Shape{    public abstract int GetArea();}class Square : Shape{    private int _side;    public Square(int n) => _side = n;    // GetArea method is required to avoid a compile-time error.    public override int GetArea() => _side * _side;    static void Main()    {        var sq = new Square(12);        Console.WriteLine($"Area of the square = {sq.GetArea()}");    }}// Output: Area of the square = 144

Abstract classes have the following features:

  • An abstract class cannot be instantiated.

  • An abstract class may contain abstract methods and accessors.

  • It is not possible to modify an abstract class with thesealed modifier because the two modifiers have opposite meanings. Thesealed modifier prevents a class from being inherited and theabstract modifier requires a class to be inherited.

  • A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.

Use theabstract modifier in a method or property declaration to indicate that the method or property does not contain implementation.

Abstract methods have the following features:

  • An abstract method is implicitly a virtual method.

  • Abstract method declarations are only permitted in abstract classes.

  • Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no curly braces ({ }) following the signature. For example:

    public abstract void MyMethod();

    The implementation is provided by a methodoverride, which is a member of a non-abstract class.

  • It is an error to use thestatic orvirtual modifiers in an abstract method declaration.

Abstract properties behave like abstract methods, except for the differences in declaration and invocation syntax.

  • It is an error to use theabstract modifier on a static property.

  • An abstract inherited property can be overridden in a derived class by including a property declaration that uses theoverride modifier.

For more information about abstract classes, seeAbstract and Sealed Classes and Class Members.

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();}

Example 2

In this example, the classDerivedClass is derived from an abstract classBaseClass. The abstract class contains an abstract method,AbstractMethod, and two abstract properties,X andY.

// Abstract classabstract class BaseClass{    protected int _x = 100;    protected int _y = 150;    // Abstract method    public abstract void AbstractMethod();    // Abstract properties    public abstract int X { get; }    public abstract int Y { get; }}class DerivedClass : BaseClass{    public override void AbstractMethod()    {        _x++;        _y++;    }    public override int X   // overriding property    {        get        {            return _x + 10;        }    }    public override int Y   // overriding property    {        get        {            return _y + 10;        }    }    static void Main()    {        var o = new DerivedClass();        o.AbstractMethod();        Console.WriteLine($"x = {o.X}, y = {o.Y}");    }}// Output: x = 111, y = 161

In the preceding example, if you attempt to instantiate the abstract class by using a statement like this:

BaseClass bc = new BaseClass();   // Error

You will get an error saying that the compiler cannot create an instance of the abstract class 'BaseClass'.

Nonetheless, it is possible to use an abstract class constructor, as in the example below

Example 3

public abstract class Shape{    public string Color { get; set; }    // Constructor of the abstract class    protected Shape(string color)    {        Color = color;        Console.WriteLine($"Created a shape with color {color}.");    }    // Abstract method that must be implemented by derived classes    public abstract double CalculateArea();}public class Square : Shape{    public double Side { get; set; }    // Constructor of the derived class calling the base class constructor    public Square(string color, double side) : base(color)    {        Side = side;    }    public override double CalculateArea()    {        return Side * Side;    }}public class Program{    public static void Main(string[] args)     {            Square square = new Square("red", 5);            Console.WriteLine($"Area of the square: {square.CalculateArea()}");                 }}

TheShape class is declaredabstract, which means it cannot be instantiated directly. Instead, it serves as a blueprint for other classes.

  • Even though you can't create objects of an abstract class, it can still have a constructor. This constructor is typicallyprotected, meaning it can only be accessed from derived classes.In this case, theShape constructor takes acolor parameter and initializes theColor property. It also prints a message to the console.Thepublic Square(string color, double side) : base(color) part calls the base class's constructor (Shape) and passes thecolor argument to it.
  • In the Shape class, the defined constructor takes a color as a parameterprotected Shape(string color). This means there's no longer a default parameterless constructor automatically provided by C# thus derived classes must use the: base(color) expression to invoke the base constructor. Setting the default value to colorprotected Shape(string color="green") will allow to omit the: base(color) expression in derived classes, still such constructorprotected Shape(string color="green") will be invoked, setting the color to green.

C# Language Specification

For more information, see theC# Language Specification. The language specification is the definitive source for C# syntax and usage.

See also

Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, seeour contributor guide.

Feedback

Was this page helpful?

YesNo

In this article

Was this page helpful?

YesNo