Unnikrishnan Unnikrishnan - 16 days ago 4x
C# Question

How to implement a derived class and call it from a Button?

I am 57 years old. Other than using C# for analysing text data, my knowledge of C# is very limited. However, occasionally I try to learn some other aspects of C#. I also prefer to understand code created for windows applications rather than for console applications.

Could anyone please elaborate on the code given below which is taken from MSDN site with simple practical examples so that I can learn something from it. I think I need to create another class but how to implement it all and call it from a button in C#. Why do they say only derived classes can call 'AddGas'. Thanks in advance.

abstract class Motorcycle
// Anyone can call this.
public void StartEngine() {/* Method statements here */ }

// Only derived classes can call this.
protected void AddGas(int gallons) { /* Method statements here */ }

// Derived classes can override the base class implementation.
public virtual int Drive(int miles, int speed) { /* Method statements here */ return 1; }

// Derived classes must implement this.
public abstract double GetTopSpeed();


Let that you want to create a specific Motorcycle for instance a Yamaha that has another method that returns the color of the Motorcycle. Instead of creating all the method in Motorcycle from scratch for each motorcycle you want to create you could inherit from it as below:

public class Yamaha : Motorcycle
    public string GetColor()
        // ....
        return "Red";

    // When a method in class is marked as abstract,
    // all the class that inherit should provide an implementation
    // of this method. Otherwise you would get a compilation error.
    public double GetTopSpeed()
        return 200;

    // When a method is marked as virtual, we have two options for the derived classes.
    // 1. Use the implementation provided int the base class.
    // 2. Override this implementation, define a method like below and provide
    // your implementation. 
    public override int Drive(int miles, int speed) 
        /* Method statements here */ return 2; 


Furthermore, it's important to note here that you can't instantiate an abstract class (you can't create an object as new Motorcycle()).

Why do they say only derived classes can call 'AddGas' ?

Because AddGas is marked as protected. Reading about access modifiers in C# would make this and other related things more clear.