Object-Oriented Programming (OOP) Concepts in C#
Object-Oriented Programming (OOP)
Concepts in C#
Class
·
A blueprint that defines
properties and methods.
·
Used to create objects.
·
Does not hold actual data itself.
Object
·
A specific instance of a class.
·
Holds data and can use the methods
defined in its class.
·
Core unit of OOP that represents
real-world entities.
Multilevel Inheritance
·
A class inherits from another
class, which in turn inherits from a third class.
·
This forms a chain of inheritance
where functionality is passed down through multiple levels.
·
Useful for creating specialized
versions of base functionality.
Hierarchical Inheritance
·
Multiple classes inherit from a
single base class.
·
Encourages reuse of common logic
in derived classes.
·
The base class acts as a parent,
and multiple child classes share its behavior.
Fields
·
Variables declared inside a class
or struct to store data.
·
Usually kept private to maintain
encapsulation.
·
Can be initialized with default
values and used internally by the class.
Properties
·
Members of a class that provide
controlled access to fields.
·
Often used for reading and writing
private data.
·
Can include logic in the get or
set methods to enforce validation or rules.
Inheritance
·
Allows one class to inherit from
another.
·
Promotes code reuse and represents
"is-a" relationships.
·
Supports single, multilevel, and
hierarchical inheritance.
·
.NET allows multiple interface
inheritance, not multiple class inheritance.
·
Uses keywords like base, virtual,
and override.
Abstraction
·
Hides complex internal details.
·
Focuses on essential features.
·
Achieved using abstract classes
and interfaces.
Encapsulation
·
Restricts direct access to
internal object data.
·
Uses access modifiers like
private, public, and protected.
·
Uses properties (getters and
setters) for data access.
Polymorphism
·
Enables methods to take many
forms.
·
Includes compile-time polymorphism
(overloading) and runtime polymorphism (overriding).
·
Enhances flexibility and
extensibility.
Interface
·
A contract with only method and
property signatures.
·
Allows multiple inheritance of
behavior.
·
Promotes loose coupling.
·
All members are abstract and
public by default.
Composition
·
One class contains objects of
another class.
·
Uses functionality of other
classes instead of inheriting from them.
·
Promotes flexibility and modular
design.
Delegates and Events
·
Delegates are type-safe method
pointers.
·
Events are based on delegates and
follow the publisher-subscriber model.
·
Used for callbacks and
event-driven programming.
Generics
·
Allow defining data types as
parameters in classes and methods.
·
Provide type safety, reusability,
and performance.
Exception Handling
·
Manages runtime errors using try,
catch, and finally blocks.
·
Ensures robust and fault-tolerant
code.
Namespaces
·
Organize code into logical groups.
·
Prevent naming conflicts.
·
Improve modularity and
readability.
Attributes
·
Metadata applied to code elements
like classes, methods, and properties.
·
Used for features like
serialization, validation, and documentation.
LINQ (Language Integrated Query)
·
Enables querying collections,
databases, XML, and more.
·
Improves code readability and
reduces boilerplate.
Async/Await and Task-Based
Asynchronous Programming
·
Simplifies writing asynchronous
code.
·
Improves responsiveness in
I/O-bound and UI-heavy applications.
Dependency Injection (DI)
·
Injects dependencies into a class
rather than hardcoding them.
·
Promotes testability and loose
coupling.
·
Supported by .NET Core using
IServiceCollection and IServiceProvider.
Lambda Expressions and Anonymous
Methods
·
Concise way to define inline
functions.
·
Commonly used with LINQ and event
handling.
Partial Classes and Methods
·
Split a single class or method
into multiple files.
·
Useful in auto-generated code and
large applications.
Extension Methods
·
Add new methods to existing types
without modifying them.
·
Commonly used for utility and
helper methods.
Records and Immutable Types
·
Introduced in C# 9.
·
Records are immutable reference
types with value-based equality.
Pattern Matching
·
Allows concise checking of types
and values.
·
Enhances readability in
conditionals and switch expressions.
Memory Management and IDisposable
·
.NET uses garbage collection for
automatic memory management.
·
IDisposable is implemented for
releasing unmanaged resources.
·
The using statement ensures proper
resource disposal.
ref
·
Passes a parameter by reference.
·
Variable must be initialized
before passing.
·
Allows modification of the
original value.
out
·
Also passes by reference,
typically used to return multiple values.
·
Variable need not be initialized
before passing.
·
Must be assigned a value inside
the method.
partial class
·
Allows a class to be defined
across multiple files.
·
All parts are merged during
compilation.
·
Helps manage large classes and
generated code.
sealed class
·
Prevents further inheritance.
·
Improves performance and control
over class design.
static class
·
Cannot be instantiated.
·
Contains only static members.
·
Ideal for utility or helper
methods.
constructor
·
Initializes a new object.
·
Can be default, parameterized, or
static.
·
Sets initial values or performs
setup tasks.
extension method
·
Adds methods to existing types
without modifying their source.
·
Enables cleaner and modular code
reuse.
collections
·
Store and manage groups of related
data.
·
Common types include List,
Dictionary, Queue, and Stack.
·
Support dynamic sizing, sorting,
filtering, and iteration.
Properties and Indexers
·
Properties provide controlled
access to class fields.
·
Include get and set accessors.
·
Can implement logic inside
accessors (e.g., validation).
·
Indexers allow accessing class
objects like arrays using index notation.
·
Useful when a class logically
represents a collection or list.
Static Members
·
Belong to the type itself, not to
any instance.
·
Shared across all instances of the
class.
·
Can include fields, properties,
methods, and constructors.
·
Useful for utilities, constants,
and global state.
Type Casting
·
Converts one data type to another.
·
Can be implicit (safe and
automatic) or explicit (requires cast operator).
·
Helps in polymorphic scenarios and
interfacing with different types.
Nested Classes
·
A class defined within another
class.
·
Can access members of the outer
class, including private members.
·
Useful for logically grouping
helper or tightly coupled functionality.
Abstract Classes
·
Cannot be instantiated directly.
·
Serve as base classes for derived
types.
·
May contain both abstract methods
(no implementation) and concrete methods.
·
Define a common template for
derived classes.
new Keyword
·
Hides a member from the base class
with the same name.
·
Used in method or property
declarations to explicitly indicate hiding behavior.
·
Can also be used to create new
instances of objects.
base Keyword
·
Refers to the base class of the
current class.
·
Used to call base class
constructors or access overridden members.
·
Helpful for extending or reusing
parent class functionality.
Events
·
Mechanism for implementing
publish-subscribe or observer pattern.
·
Built on delegates and used to
signal state changes or user actions.
·
Allow subscribers to respond to
occurrences without tight coupling.
Delegates
·
Type-safe function pointers.
·
Store references to methods with a
specific signature.
·
Can be passed as arguments,
returned from methods, or used for callbacks.
Reflection
·
Enables inspection of metadata
about types at runtime.
·
Can dynamically create instances,
invoke methods, or access properties.
·
Useful in frameworks,
serialization, dependency injection, and tooling.
Records
·
Introduced in C# 9 for immutable
reference types.
·
Support value-based equality
comparison.
·
Automatically implement members
like equality, cloning, and deconstruction.
·
Ideal for data transfer and
read-only models.
Object Pooling
·
Reuses objects instead of creating
and destroying them frequently.
·
Reduces memory allocation and
garbage collection overhead.
·
Useful in high-performance
scenarios like game development or web servers.
Immutable Objects
·
Cannot be changed after creation.
·
All state is set via constructor
and remains constant.
·
Ensures thread safety and
predictable behavior.
·
Examples include strings and
records.
Mutable Objects
·
Can change state after creation.
·
Allow updating properties and
fields.
·
Easier to work with in dynamic or
interactive systems but require careful management in multi-threaded scenarios.
Access Modifiers
Define the visibility of classes
and their members:
·
public – Accessible from anywhere.
·
private – Accessible only within
the same class.
·
protected – Accessible within the
same class and derived classes.
·
internal – Accessible within the
same assembly.
·
protected internal – Accessible
within the same assembly or derived classes in other assemblies.
Static vs Instance Members
·
Static members belong to the class
itself; shared across all instances.
·
Instance members belong to a
specific object instance.
·
Static members are used for global
logic or utility methods.
·
Instance members hold unique data
and behavior for each object.
Value Types
·
Store data directly.
·
Typically allocated on the stack.
·
Includes types like int, float,
bool, and structs.
·
Faster access but copied by value
(not by reference).
Reference Types
·
Store a reference to the data
(address in memory).
·
Allocated on the heap.
·
Includes classes, interfaces,
arrays, and delegates.
·
Changes to a reference affect all
references to the same object.
Object Finalization
·
Finalization is a cleanup process
triggered before the object is removed from memory.
·
Achieved by overriding the
Finalize method (not recommended for most use cases).
·
Best practice is to use the
IDisposable interface and dispose pattern for deterministic cleanup.
Garbage Collection (GC)
·
Automatic memory management in
.NET.
·
Frees unused objects from memory
to prevent leaks.
·
Occurs in generations (0, 1, 2)
based on object lifespan.
·
Developers can call GC.Collect()
but should do so cautiously.
Anonymous Types
·
Lightweight types created on the
fly using var.
·
Contain read-only properties with
no explicit class definition.
·
Useful in LINQ queries or
temporary data grouping.
Covariance and Contravariance in
Generics
·
Covariance allows a method to
return a more derived type than specified (output).
§
Enables assignment of a more
derived type to a base generic interface (e.g., IEnumerable<Animal> from
IEnumerable<Dog>).
·
Contravariance allows a method to
accept a more general type than specified (input).
§
Enables assignment of a base type
to a more derived generic delegate (e.g., Action<Dog> from
Action<Animal>).
·
Improves flexibility in method
parameters and return types.
Readonly, Const, Let, Var
·
const:
Defines compile-time constant values, must be assigned at declaration, cannot
change.
·
readonly:
Runtime constant, can be assigned once during declaration or in constructor,
used for instance or static fields.
·
var:
Implicitly typed local variable, type inferred at compile time, must be
initialized.
·
let: (Not
a C# keyword; used in LINQ queries to introduce range variables.)
Variables and Data Types
·
Variables store data and have a
specific data type (int, string, bool, etc.).
·
Strongly typed: type checked at
compile time.
·
Common types: int, double, char,
bool, string, decimal, object.
·
Type inference available with var.
Method Overloading and Overriding
·
Overloading: Same method name,
different parameters within the same class.
·
Overriding: Derived class provides
specific implementation of a virtual method in base class using override.
·
Requires base method marked
virtual, abstract, or override.
Indexers
·
Allow objects to be indexed like
arrays.
·
Define get/set accessors using
this keyword with parameters.
·
Useful for custom collections or
data structures.
Anonymous Methods
·
Inline unnamed methods.
·
Syntax: delegate(parameters) { /*
code */ }.
·
Useful for event handlers and
callbacks before lambdas.
Lambda Expressions
·
Concise syntax for anonymous
functions: (parameters) => expression.
·
Used heavily in LINQ, delegates,
and events.
·
Can have statement bodies with {}.
Tuples
·
Group multiple values into a
single object without defining a class.
·
Can be named or unnamed.
·
Support deconstruction into
individual variables.
Generics (classes, methods,
constraints)
·
Allow type parameters in
classes/methods for type safety and reuse.
·
Constraints restrict allowed types
(where T : class, where T : new(), etc.).
·
Used in collections and utility
classes.
Nullable Types and Null Coalescing
Operator
·
Nullable types allow value types
to hold null (int?).
·
Null coalescing operator ??
returns left operand if not null, otherwise right operand.
·
Simplifies null handling.
Dynamic Types
·
dynamic bypasses compile-time type
checking.
·
Type resolved at runtime.
·
Useful for COM interop,
reflection, or scripting scenarios.
Garbage Collection (GC)
·
Automatic memory management by .NET
runtime.
·
Frees unused objects to reclaim
memory.
·
Uses generations (0,1,2) for
efficient cleanup.
Boxing and Unboxing
·
Boxing: converting value type to
object type (heap allocation).
·
Unboxing: converting object back
to value type.
·
Expensive operations; avoid in
performance-critical code.
Value Types vs Reference Types
·
Value types: stored on stack, hold
actual data (int, struct).
·
Reference types: stored on heap,
hold reference to data (class, string).
·
Value types copied on assignment;
reference types copied by reference.
Structs and Enums
·
Structs: lightweight value types,
used for small data structures.
·
Cannot have inheritance (except
from interfaces).
·
Enums: named constants of integral
types.
Arrays and Multi-dimensional
Arrays
·
Fixed-size collections of elements
of the same type.
·
Single-dimensional,
multi-dimensional (rectangular), and jagged arrays supported.
IEnumerable and IEnumerator
Interfaces
·
IEnumerable: supports simple
iteration over a collection.
·
IEnumerator: supports enumerating
through a collection (MoveNext, Current, Reset).
·
Used for foreach loops.
LINQ Queries on Collections
·
Language Integrated Query to
filter, project, and aggregate data.
·
Supports query syntax and method
syntax.
·
Works on any IEnumerable or
IQueryable.
ReadOnlyCollections
·
Wrappers around collections that
prevent modification.
·
Provide safe, immutable views of
data.
Threading Basics (Thread class,
ThreadPool)
·
Thread: manual thread creation and
management.
·
ThreadPool: managed pool of
threads for background tasks, more efficient than creating threads manually.
Task Parallel Library (TPL)
·
Abstraction for parallel and
asynchronous programming.
·
Uses Task objects for managing
concurrent operations.
·
Simplifies thread management and
synchronization.
async/await for Asynchronous
Programming
·
Keywords to write asynchronous
code that looks synchronous.
·
Improves UI responsiveness and
scalability.
·
Works with Task and Task<T>.
Cancellation Tokens
·
Cooperative cancellation of async
or long-running operations.
·
Passed to methods to signal
cancellation requests.
Locks, Mutex, Monitor for
Synchronization
·
Tools to prevent race conditions
and ensure thread safety.
·
lock statement uses Monitor
internally.
·
Mutex allows cross-process
synchronization.
Records (C# 9+)
·
Reference types with built-in
immutability and value-based equality.
·
Simplify creating data transfer
objects.
Init-only Setters
·
Properties that can only be set
during object initialization.
·
Allow immutable object
initialization with flexible syntax.
Top-level Statements
·
Simplify program entry point by
removing explicit Main method.
·
Useful for small programs and
scripts.
Pattern Matching Enhancements
(switch expressions, relational patterns)
·
More expressive and concise type
checks and value matching.
·
Support complex conditions
directly in switch expressions.
Source Generators
·
Compile-time code generation
feature.
·
Helps reduce boilerplate and
improve performance.
Nullable Reference Types
·
Compiler feature to distinguish
nullable vs non-nullable references.
·
Helps avoid null reference
exceptions by enforcing annotations.
List
·
Dynamic array-based collection.
·
Allows duplicate elements.
·
Maintains insertion order.
·
Provides fast indexed access
(constant time).
·
Automatically resizes as elements
are added.
·
Commonly used when order matters
and frequent access by index is required.
Dictionary<TKey, TValue>
·
Collection of unique keys mapped
to values.
·
Keys must be unique; values can
repeat.
·
Provides fast lookup, insertion,
and removal by key.
·
Average lookup time is constant.
·
Useful for key-value pair storage
and retrieval scenarios.
HashSet
·
Collection of unique elements, no
duplicates allowed.
·
Unordered collection (no
guaranteed order).
·
Provides fast addition, removal,
and lookup.
·
Supports set operations like
union, intersection, and difference.
·
Ideal for membership tests and
when uniqueness is important.
Queue
·
First-In-First-Out (FIFO)
collection.
·
Enqueue adds an element to the
end.
·
Dequeue removes the element from
the front.
·
Suitable for scenarios like task
scheduling or breadth-first search.
·
Maintains order of processing
based on insertion time.
Stack
·
Last-In-First-Out (LIFO)
collection.
·
Push adds an element on top.
·
Pop removes the element from the
top.
·
Useful for undo operations,
recursive algorithms, and backtracking.
·
Processes elements in reverse
order of insertion.
Default Constructor
·
A parameterless constructor that
initializes an object with default values.
·
Automatically created by the
compiler if no other constructor is defined.
·
Often used when no specific
initialization is required.
Static Constructor
·
Runs only once for the type, not
per instance.
·
Used to initialize static data or
perform actions before any instance is created.
·
Called automatically by the
runtime and cannot be called directly.
Primary Constructor (C# 12)
·
Constructor parameters are
declared directly in the class definition.
·
Allows compact syntax and
initialization at the point of declaration.
·
Useful for immutable or record-like
types.
Private Constructor
·
Restricts object creation from
outside the class.
·
Commonly used in Singleton
patterns or static utility classes.
·
Prevents instantiation while
allowing internal logic to function.
Overloaded Constructor
·
Multiple constructors with
different parameter lists.
·
Provides flexibility by allowing
different ways to initialize an object.
·
Helps handle various
initialization scenarios.
Chained Constructor
·
One constructor calls another
within the same class.
·
Reduces code duplication when
multiple constructors share logic.
·
Uses internal delegation for
consistency.
Base Constructor
·
A constructor in a derived class
that calls the constructor of its base class.
·
Ensures that the base class is
properly initialized before the derived class adds its own logic.
·
Important in inheritance chains.
Optional Parameters Constructor
·
A constructor with parameters that
have default values.
·
Allows method or constructor calls
without supplying all arguments.
·
Improves usability by simplifying
calls for common cases.
Types of Constructors in C#
1.
Default Constructor
2.
Parameterized Constructor
3.
Copy Constructor
4.
Static Constructor
5.
Private Constructor
6.
Constructor Overloading
7.
Chained Constructor (this)
8.
Base Constructor (base)
9.
Constructor with Optional
Parameters
Types of Inheritance in C#
1.
Single Inheritance
2.
Multilevel Inheritance
3.
Hierarchical Inheritance
4.
Hybrid Inheritance (via
interfaces)
5.
Interface Inheritance
6.
Multiple Inheritance (only via
interfaces)
Comments
Post a Comment