Can someone explain: override,abstract and virtual?

Hi so I’m having trouble understanding what each bit does?? Also if someone could tell me what would be the best for a base class???

thx <3

1 Like

About the C# Player’s Guide (csharpplayersguide.com)

This might be the book for you @Shawty

I recently completed it, highly recommend joining their Discord.

Its very hard to read lots of dry documentation - but its also very hard to simplify it to the point of getting the concepts. But I’ll give it a shot. (20 years of C# speaking)

classes used as a base-class
All it means, is I create a class that inherit from some other class. For example, you might create a class to represent sprites in your game. Then you find that you need a more specialised kind of sprite to represent the main player on screen, but the main player is also a sprite. This means when you have “class PlayerSprite : Sprite” you also put a player instance in a collection of Sprite instances, such as a List because the PlayerSprite class IS A Sprite instance, just a more specialised kind.

classes as abstract

When you have methods, and/or properties that you want to share, but the class itself doesn’t make sense, as it may be incomplete - and needs more to make it useful. For example, you may never want to create an instance of an Animal, as its too abstract, where as a class like Dog:Animal makes more sense. So adding ‘abstract’ to the Animal definition - “abstract class Animal” means you enforce the fact no one can make an instance of that type, but are free to inherit from it.

methods as abstract

The biggest benefit of abstract methods, is that you can write code in your abstract class that calls the abstract method - more on that in a second. You then inherit from your abstract class, and are forced to implement the abstract methods. Which means you’re not providing any base functionality unlike a virtual method. The inheriting class must provide the real code. Back in the base class then, you can write methods that call the abstract method, and in reality, it will call the implementation provided by the inheriting class. Therefore a Cat:Animal could provide a different implementation for an abstract method called “MakeANoise()” that what a Dog:Animal will provide. This is a powerful concept to grasp.

methods as virtual / override

Unlike an abstract method, a virtual method is optional. You can provide code in a base-class, and optionally override it. Simplest example is “.ToString()” method. By default that will return the name of your type. But you can optionally choose to override this method, and represent some value of the class, for example “I am a Dog, and I make a Bark! noise”.
Often I use this to provide some debugging information. When debugging in Visual Studio, it uses the “.ToString()” when you hover over a collection of a type, such as Animal. In this case, it would give me more useful information. But this technique has many many possibilities, and is incredibly powerful in altering the behaviour of a class. (side effects).

I hope this gives a little insight - and if you’re hungry for more, hit the Microsoft docs!
class keyword - C# Reference - C# | Microsoft Learn

// In C#, override, abstract and virtual are keywords that are used to define the behavior of methods in classes and interfaces. Let’s see what they mean and how they work.

// A method is a block of code that performs a specific task, such as adding two numbers or printing a message. A method can have a name, parameters and a return value. For example:

public int Add(int x, int y) // This is a method named Add that takes two integers as parameters and returns their sum
{
    return x + y; // This is the body of the method that contains the code to execute
}

// A class is a blueprint for creating objects, which are instances of the class. A class can have fields, properties and methods that define the state and behavior of the objects. For example:

public class Calculator // This is a class named Calculator
{
    public int Add(int x, int y) // This is a method of the class that can be called by the objects
    {
        return x + y;
    }
}

// An interface is a contract that specifies what methods a class must implement if it wants to conform to the interface. An interface does not provide any implementation for the methods, it only declares their names, parameters and return values. For example:

public interface ICalculator // This is an interface named ICalculator
{
    int Add(int x, int y); // This is a method declaration that does not have a body
}

// A class can implement an interface by using the colon (:slight_smile: operator and providing the implementation for all the methods declared in the interface. For example:

public class SimpleCalculator : ICalculator // This is a class named SimpleCalculator that implements the ICalculator interface
{
    public int Add(int x, int y) // This is the implementation of the Add method declared in the interface
    {
        return x + y;
    }
}

// Now, let’s see what override, abstract and virtual mean.

// Override is a keyword that is used to modify a method in a derived class that has the same name and signature as a method in a base class. A derived class is a class that inherits from another class, which is called the base class. For example:

public class Animal // This is a base class named Animal
{
    public virtual void MakeSound() // This is a method named MakeSound that can be overridden by derived classes
    {
        Console.WriteLine("Generic animal sound");
    }
}

public class Dog : Animal // This is a derived class named Dog that inherits from Animal
{
    public override void MakeSound() // This is a method named MakeSound that overrides the method in the base class
    {
        Console.WriteLine("Woof");
    }
}

// In this example, the Animal class has a method named MakeSound that prints “Generic animal sound”. The Dog class inherits from Animal and overrides the MakeSound method to print “Woof”. The override keyword indicates that this method replaces the behavior of the method in the base class.

// Abstract is a keyword that is used to declare a method or a class that cannot be instantiated or implemented directly. An abstract method is a method that has no body and must be overridden by derived classes. An abstract class is a class that has at least one abstract method and cannot be used to create objects. For example:

public abstract class Shape // This is an abstract class named Shape
{
    public abstract double Area(); // This is an abstract method named Area that must be overridden by derived classes
}

public class Circle : Shape // This is a derived class named Circle that inherits from Shape
{
    private double radius; // This is a field of the class

    public Circle(double radius) // This is a constructor of the class that takes the radius as a parameter
    {
        this.radius = radius; // This assigns the parameter value to the field
    }

    public override double Area() // This is a method named Area that overrides the abstract method in the base class
    {
        return Math.PI * radius * radius; // This returns the area of the circle using the formula pi * r^2
    }
}

// In this example, the Shape class is an abstract class that has an abstract method named Area. The Circle class inherits from Shape and overrides the Area method to provide the implementation for calculating the area of a circle. The abstract keyword indicates that this class or method cannot be used directly and must be inherited or overridden.

// Virtual is a keyword that is used to declare a method that can be overridden by derived classes, but also has a default implementation in the base class. A virtual method is similar to an abstract method, but it provides a body that can be executed if no derived class overrides it. For example:

public class Vehicle // This is a base class named Vehicle
{
    public virtual void Start() // This is a virtual method named Start that can be overridden by derived classes
    {
        Console.WriteLine("Starting the vehicle");
    }
}

public class Car : Vehicle // This is a derived class named Car that inherits from Vehicle
{
    public override void Start() // This is a method named Start that overrides the virtual method in the base class
    {
        Console.WriteLine("Starting the car");
    }
}

public class Bicycle : Vehicle // This is a derived class named Bicycle that inherits from Vehicle
{
    // This class does not override the Start method
}

// In this example, the Vehicle class has a virtual method named Start that prints “Starting the vehicle”. The Car class inherits from Vehicle and overrides the Start method to print “Starting the car”. The Bicycle class also inherits from Vehicle, but does not override the Start method, so it uses the default implementation from the base class. The virtual keyword indicates that this method can be overridden, but also has a fallback behavior.

// I hope this explanation helps you understand the meaning and usage of override, abstract and virtual keywords in C# code. If you have any questions, feel free to ask me.

Hope that helps…