create a subclass in csharp

To create a subclass in C#, you can use the inheritance concept to derive a new class from an existing class. By doing this, the subclass can inherit all the data and behavior of its parent class, and also override or extend the parent class's methods.

Here is an example of how to create a basic subclass in C#:

main.cs
// Parent class
public class Animal {
    public string Name { get; set; }
    public int Age { get; set; }
    public virtual void MakeSound() {
        Console.WriteLine("Some generic animal sound");
    }
}

// Subclass derived from Animal class
public class Dog : Animal {
    public void Bark() {
        Console.WriteLine("Woof!");
    }
    
    // Override parent MakeSound method
    public override void MakeSound() {
        Console.WriteLine("Bark bark!");
    }
}
477 chars
21 lines

In this example, the Animal class is the parent class, and the Dog class is the subclass derived from Animal class. The Dog class has its own Bark method and overrided the parent MakeSound method which now writes "Bark bark!" to the console.

You can create instances of the subclass just like a typical object using the derived class constructor:

main.cs
Dog myDog = new Dog();
myDog.Name = "Fido";
myDog.Age = 2;
myDog.Bark(); // Output: Woof!
myDog.MakeSound(); // Output: Bark bark!
131 chars
6 lines

gistlibby LogSnag