Object-Oriented Programming in C#
C# is fundamentally an object-oriented language. OOP organises software around objects that encapsulate data and behaviour. The four pillars are encapsulation, inheritance, polymorphism, and abstraction.
Classes and Objects
A class is a blueprint defining fields, properties, methods, and events. An object is an instance of a class created with the new keyword. Constructors initialise objects; destructors (finalizers) clean up. C# supports static classes and members shared across all instances.
Encapsulation
Encapsulation bundles data with methods that operate on it and restricts direct access. Access modifiers control visibility: public (accessible everywhere), private (class only), protected (class and subclasses), internal (same assembly), and protected internal. Properties (get/set accessors) provide controlled access to fields.
Inheritance
Inheritance allows a derived class to inherit members from a base class. C# supports single inheritance (one base class) but multiple interface implementation. The base keyword accesses base class members. sealed prevents further inheritance.
Polymorphism
Polymorphism means many forms. Compile-time polymorphism is achieved through method overloading and operator overloading. Runtime polymorphism uses virtual methods in the base class and override in derived classes. The abstract keyword creates methods that must be overridden.
Abstract Classes and Interfaces
An abstract class cannot be instantiated and may contain abstract (unimplemented) and concrete methods. An interface defines a contract of methods, properties, and events without implementation (C# 8+ allows default implementations). A class can implement multiple interfaces, enabling a form of multiple inheritance.
Delegates and Events
A delegate is a type-safe function pointer that references methods with a matching signature. Events are based on delegates and implement the publisher-subscriber pattern. Lambda expressions (=>) provide concise anonymous methods. Built-in delegates include Action, Func, and Predicate.
Generics and Collections
Generics allow type-safe data structures and methods: List<T>, Dictionary<TKey, TValue>, Queue<T>, Stack<T>. They avoid boxing/unboxing overhead and provide compile-time type checking. The System.Collections.Generic namespace contains generic collection classes.
Summary
OOP in C# builds on classes, encapsulation, inheritance, and polymorphism. Advanced features like interfaces, delegates, events, and generics make C# a powerful language for building complex, maintainable applications.