In C#, classes are the fundamental building blocks of object-oriented programming (OOP). They define objects by combining data (fields/properties) and methods (functions). There are several types of classes in C#, each serving a different purpose:
1. Concrete Classes
A typical class that defines members (fields, properties, methods) and can be instantiated. This is the most common type of class in C#.
public class Car
{
public string Make { get; set; }
public string Model { get; set; }
public void Drive()
{
Console.WriteLine("Car is driving.");
}
}
2. Static Classes
Static classes cannot be instantiated and can only contain static members. They are commonly used to group related utility methods.
- Key characteristics:
- All members must be
static
. - The class itself cannot be instantiated.
- Useful for utility methods or global state.
- All members must be
public static class MathUtility
{
public static int Add(int a, int b)
{
return a + b;
}
}
3. Abstract Classes
Abstract classes cannot be instantiated directly. They serve as base classes and provide shared functionality to derived classes. They may contain both abstract members (methods without implementation) and concrete members (methods with implementation).
- Key characteristics:
- Used to define common behavior.
- May include abstract members that derived classes must implement.
- Can contain fields, properties, and methods.
public abstract class Animal
{
public abstract void Speak(); // Abstract method without implementation
public void Sleep() // Concrete method with implementation
{
Console.WriteLine("Animal is sleeping.");
}
}
public class Dog : Animal
{
public override void Speak()
{
Console.WriteLine("Dog barks.");
}
}
4. Sealed Classes
Sealed classes cannot be inherited. They are used when you want to prevent further derivation of a class.
- Key characteristics:
- Prevents other classes from extending it.
- Useful when you want to avoid misuse or unwanted inheritance.
public sealed class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
}
5. Partial Classes
Partial classes allow you to split the implementation of a class into multiple files. This can be useful in large projects to organize code better.
- Key characteristics:
- All parts of the class must be defined with the
partial
keyword. - Combined into a single class when the code is compiled.
- All parts of the class must be defined with the
// File1.cs
public partial class Person
{
public string FirstName { get; set; }
}
// File2.cs
public partial class Person
{
public string LastName { get; set; }
}
6. Nested Classes
A class defined within another class. Nested classes are often used to logically group classes that are only used in the context of their containing class.
- Key characteristics:
- Access modifiers of the nested class can be controlled (public, private, etc.).
- Can access private members of the containing class.
public class OuterClass
{
private int outerField = 10;
public class NestedClass
{
public void Display()
{
Console.WriteLine("Inside Nested Class");
}
}
}
7. Generic Classes
A generic class allows the use of type parameters, providing flexibility and type safety. It enables the class to work with different data types without losing type safety.
- Key characteristics:
- Type parameters (e.g.,
T
) are used to specify the data types that will be used when the class is instantiated. - Can handle different types in a type-safe manner.
- Type parameters (e.g.,
public class Box<T>
{
private T item;
public void Add(T newItem)
{
item = newItem;
}
public T GetItem()
{
return item;
}
}
var intBox = new Box<int>();
intBox.Add(10);
var stringBox = new Box<string>();
stringBox.Add("Hello");
8. Records (Introduced in C# 9.0)
Records are a special type of class optimized for immutability and value-based equality. They are commonly used for creating simple data models.
- Key characteristics:
- Provides a concise way to create immutable objects.
- Supports value-based equality (compares content rather than reference).
public record Person(string FirstName, string LastName);
var person1 = new Person("John", "Doe");
var person2 = new Person("John", "Doe");
// True because the values are the same, not the reference
Console.WriteLine(person1 == person2);
9. Anonymous Classes
Anonymous classes are used for creating objects without explicitly defining a class. This is typically used in scenarios like LINQ queries or temporary data structures.
- Key characteristics:
- Created inline without a class definition.
- Mainly used for simple, temporary data structures.
var person = new { FirstName = "John", LastName = "Doe" };
Console.WriteLine(person.FirstName); // Output: John
10. Extension Classes
Extension classes are used to add new methods to existing types without modifying their original source code. Extension methods are declared as static methods in static classes.
- Key characteristics:
- Extends functionality of existing types.
- Defined in static classes and use
this
keyword to refer to the type being extended.
public static class StringExtensions
{
public static bool IsUpperCase(this string input)
{
return input == input.ToUpper();
}
}
var test = "HELLO";
Console.WriteLine(test.IsUpperCase()); // True
11. Singleton Classes
The Singleton pattern ensures that a class has only one instance and provides a global point of access to it. In C#, you can implement a Singleton class by making the constructor private and providing a static instance.
public class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton() { }
public static Singleton Instance
{
get { return instance; }
}
}