Curriculum
In C#, a base class is a class that serves as a starting point for other classes that inherit from it. When a class inherits from a base class, it can use all the members (fields, properties, methods, etc.) of the base class as if they were its own.
Here’s an example of a base class in C#:
public class Animal { public int Age { get; set; } public string Name { get; set; } public void Sleep() { Console.WriteLine("Zzzzzzz..."); } public void Eat() { Console.WriteLine("Yum!"); } }
In this example, the Animal
class is a base class. It contains two properties (Age
and Name
) and two methods (Sleep
and Eat
).
To inherit from a base class, we use the :
symbol followed by the name of the base class. Here’s an example:
public class Cat : Animal { public void Meow() { Console.WriteLine("Meow!"); } }
In this example, the Cat
class inherits from the Animal
class. It contains one method (Meow
). Because Cat
inherits from Animal
, it can use the Age
, Name
, Sleep
, and Eat
members of the Animal
class.
When a class inherits from a base class, it can use the members of the base class directly or override them. Here’s an example:
public class Dog : Animal { public new void Eat() { Console.WriteLine("Nom nom nom!"); } }
In this example, the Dog
class also inherits from the Animal
class. It contains one method (Eat
). However, the Eat
method in the Dog
class has the new
keyword, which means that it overrides the Eat
method in the Animal
class. When we call the Eat
method on a Dog
instance, it will use the Eat
method from the Dog
class instead of the Eat
method from the Animal
class.
Here are some rules to keep in mind when working with base classes in C#:
base
keyword to call the original implementation of the member from the base class.In summary, a base class in C# is a class that serves as a starting point for other classes that inherit from it. When a class inherits from a base class, it can use all the members of the base class as if they were its own. By leveraging base classes, we can create more flexible and reusable code that can handle a variety of situations.