add a method to a subclass in csharp

To add a method to a subclass in C#, you can simply define a new method within the subclass using the public access modifier. This method can then be called on instances of the subclass.

However, if you want to override a method that is already defined in the superclass, you can use the override keyword. This allows you to provide a new implementation for the method in the subclass.

Here's an example of how to add a new method to a subclass:

main.cs
class Animal {
    public void Eat() {
        Console.WriteLine("The animal is eating.");
    }
}

class Dog : Animal {
    public void Bark() {
        Console.WriteLine("The dog is barking.");
    }
}

Dog myDog = new Dog();
myDog.Bark(); // Output: The dog is barking.
273 chars
15 lines

In this example, we create a superclass Animal with a method Eat. We then create a subclass Dog with a method Bark. The Bark method is only defined in the Dog subclass and can be called on Dog instances, but not on Animal instances.

If we wanted to override the Eat method in the Dog subclass, we could define a new implementation using the override keyword, like this:

main.cs
class Animal {
    public virtual void Eat() {
        Console.WriteLine("The animal is eating.");
    }
}

class Dog : Animal {
    public override void Eat() {
        Console.WriteLine("The dog is eating.");
    }

    public void Bark() {
        Console.WriteLine("The dog is barking.");
    }
}

Dog myDog = new Dog();
myDog.Eat(); // Output: The dog is eating.
368 chars
19 lines

In this example, we override the Eat method in the Dog subclass using the override keyword. We also mark the Eat method in the Animal class as virtual to allow it to be overridden in subclasses. Now, when we call the Eat method on a Dog instance, it will use the implementation defined in the Dog subclass, rather than the implementation defined in the Animal superclass.

gistlibby LogSnag