Note
You can check other posts on my personal website: https://hbolajraf.net
In C#, classes are the building blocks of object-oriented programming. They encapsulate data for the object and define methods to manipulate that data. There are various types of classes in C#, each serving different purposes. Let’s explore them with detailed examples.
1. Regular Classes
Regular classes are the most common type of classes in C#. They are used to define objects and their behavior.
Example:
{
public string Name { get; set; }
public int Age { get; set; }
public void PrintDetails()
{
Console.WriteLine($”Name: {Name}, Age: {Age}“);
}
}
In this example, we define a Person class with properties Name and Age, and a method PrintDetails() to print the person’s details.
2. Abstract Classes
Abstract classes are used as base classes and cannot be instantiated directly. They can contain abstract methods that must be implemented by derived classes.
Example:
{
public abstract double Area();
}
public class Rectangle : Shape
{
public double Length { get; set; }
public double Width { get; set; }
public override double Area()
{
return Length * Width;
}
}
In this example, Shape is an abstract class with an abstract method Area(). Rectangle is a concrete class that derives from Shape and implements the Area() method.
3. Static Classes
Static classes cannot be instantiated and can only contain static members. They are often used to group related utility methods together.
Example:
{
public static int Add(int a, int b)
{
return a + b;
}
public static int Multiply(int a, int b)
{
return a * b;
}
}
In this example, MathUtils is a static class containing static methods for addition and multiplication.
4. Sealed Classes
Sealed classes cannot be inherited. They are often used to prevent further derivation or to increase security.
Example:
{
public void Method()
{
Console.WriteLine(“Method in FinalClass”);
}
}
In this example, FinalClass is a sealed class that cannot be inherited by other classes.
5. Partial Classes
Partial classes allow a class’s members to be defined in multiple files. They are often used in large projects to organize code.
Example:
File 1 (Person.cs):
{
public string Name { get; set; }
}
File 2 (PersonAdditional.cs):
{
public int Age { get; set; }
}
In this example, Person is defined across two files, each containing a partial definition of the class.
What Next?
Understanding the different types of classes in C# is crucial for building robust and maintainable applications. Whether it’s regular classes for defining objects, abstract classes for defining base behavior, static classes for utility methods, sealed classes for security, or partial classes for organizing code, each type has its own purpose and use cases. Choose the appropriate type based on your requirements and design principles.