C# Abstract Keyword

C# Code Snippets Abstract Keyword
Share:

About

In this code snippet, we’ll find out what the abstract keyword does in C#.

Classes and their members such as methodsproperties, … that are marked with abstract keyword aren’t fully implemented. Abstract classes aren’t meant to be instantiated but are only meant to be inherited from. This means that class members(methods, properties, …) marked with the abstract keyword must be implemented in the child class.

Let’s look at the example below. 

Code:

using System;

namespace AbstractClass
{
    class Program
    {
        static void Main(string[] args)
        {
            MyChildClass MCC = new MyChildClass();

            MCC.myAbstractMethod();

            Console.ReadLine();
        }
    }

    //This abstract class can't be instantiated. It can only be used to inherit from.
    //Abstract members will have to be implemented in the derived class.
    abstract class MyClass
    {
        public abstract void myAbstractMethod();
    }

    class MyChildClass : MyClass
    {
        //Implementation of the myAbstractMethod() method.  
        public override void myAbstractMethod()
        {
            Console.WriteLine("From myAbstractMethod.");
        }
    }
}

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger