C# Tutorials
C# Methods
C# Classes
C# Examples
In C #, you may have acquired fields and routes from one class to another. We combine the concept of an inheritance into two categories:
To inherit a classroom, use: a symbol.
In the example below, the Car class (child) inherits the fields and methods from the Vehicle (parent) category:
class Vehicle // base class (parent)
{
public string brand = "Ford"; // Vehicle field
public void honk() // Vehicle method
{
Console.WriteLine("Tuut, tuut!");
}
}
class Car : Vehicle // derived class (child)
{
public string modelName = "Mustang"; // Car field
}
class Program
{
static void Main(string[] args)
{
// Create a myCar object
Car myCar = new Car();
// Call the honk() method (From the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand field (from the Vehicle class) and the value of the modelName from the Car class
Console.WriteLine(myCar.brand + " " + myCar.modelName);
}
}
If you do not want other classes to inherit a classroom, use a sealed keyword:
If you try to access a sealed class, C# will generate an error:
sealed class Vehicle
{
...
}
class Car : Vehicle
{
...
}