The ASP Dotent Core OOPs
The ASP Dotent Core OOPs
ASP.NET Core benefits greatly from OOP because it allows developers to:
Encapsulate Data and Behaviour: By using classes, you can encapsulate data
and methods, which helps in organizing and protecting the internal state of
objects.
Reuse Code Efficiently: Inheritance enables the creation of new classes based
on existing ones, promoting code reuse, and reducing redundancy.
Enhance Flexibility and Scalability: Polymorphism allows objects to be treated
as instances of their parent class, enabling flexibility in how objects interact and
are manipulated.
Create Maintainable Code: Abstraction helps in managing complexity by
allowing developers to focus on high-level operations while hiding implementation
details.
Think of a class as a recipe, and an object as the dish you prepare from that recipe. For
example, in a library system, a Book class might include properties like “Title”, “Author”
and “ReleaseDate” and methods like “Borrow” and “Return”.
This class defines a Book with properties such as Title, Author, Genre, and ReleaseDate.
Benefits of OOP
By adopting OOP, developers can create more organized and scalable software,
which is especially useful in ASP.NET Core applications.
1. Abstraction
In this example, the Car class abstracts away the engine details, focusing on
functionalities like driving and braking.
2. Encapsulation
Encapsulation bundles data (attributes) and related operations (methods) within a class.
It controls access to this internal data using access modifiers (public, private, protected).
This ensures data integrity and prevents unauthorized modifications.
Here, the _speed attribute is private, ensuring it can only be modified through the public
Drive method. This enforces data integrity and prevents unintended changes.
3. Inheritance
Inheritance allows creating new classes (subclasses) based on existing classes (base
classes). The subclass inherits properties and methods from the base class, promoting
code reusability.
4. Polymorphism
For example, consider a method MakeSound defined in both Car and Truck classes:
Here, the MakeSound method is overridden in both Car and Truck. When calling
MakeSound on an object of either class, the appropriate version executes based on the
object's type. This demonstrates polymorphic behaviour.
Prerequisites
To follow along with this sample application, you need to have installed a recent version
of .NET, the latest version is .NET 8 and Visual Studio 2022 (latest version
recommended).
Project Structure
Once the project is created, you will see a default folder structure.
Add a new folder named Models to hold your entity classes.
Implementing Abstraction
In this class, we abstract the bank account entity, which includes properties like account
holder, balance, and created date.
Implementing Encapsulation
Encapsulation means hiding the internal details of a class and providing controlled
access through access modifiers. C# offers several access modifiers:
In this example, accounts is a private list that stores the bank accounts. The AddAccount,
RemoveAccount, and GetAccounts methods provide controlled access to this list,
encapsulating the data and behaviour within the Bank class.
Implementing Inheritance
Inheritance allows a class to inherit properties and methods from another class. We’ll
create a new SavingsAccount class that inherits from BankAccount and adds additional
properties specific to savings accounts.
The SavingsAccount class inherits from BankAccount, gaining its properties while adding
an additional InterestRate property.
Implementing Polymorphism
Interfaces define a contract that classes must implement, providing a common set of
methods for different classes to implement in their own way.
In the example above, any class implementing the ITransaction interface must provide
an implementation for the Process method, ensuring that different types of transactions
can be handled uniformly.
Methods and properties define the behaviour and characteristics of classes. Methods
perform actions, and properties provide access to internal data.
In this example, the Deposit and Withdraw methods allow for actions to be performed on
the Balance property, encapsulating the logic to ensure the balance is correctly modified
and never goes negative.
Constructors initialize objects when they are created, while destructors release resources
when an object is destroyed.
In the example, the constructor initializes the BankAccount with an initial balance, while
the destructor contains logic to clean up resources when the account is no longer
needed.
Static Classes
Static classes contain static members that can be accessed without creating an instance
of the class. This is useful for utility or helper functions that are shared across the
application.
The InterestCalculator class provides a static method CalculateInterest that can be used
anywhere in the application without needing to create an instance of the class.
Namespaces
Namespaces organize and group related classes into a hierarchy, helping to avoid name
conflicts and to modularize the code, making it more manageable and readable.
ASP.NET Core frequently uses object-oriented design patterns such as MVC (Model-View-
Controller) to separate business logic, presentation, and user interaction, promoting
organized and maintainable code.
Example:
In the MVC pattern, the Controllers handle user input, the Models represent the data, and
the Views display the data. This separation of concerns makes the application easier to
manage and scale.
----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
Console.WriteLine("Car is driving!");
Console.WriteLine("Car is braking!");
----------------------------------------------------------------------------------
{
private int _speed; // Private attribute (encapsulated)
_speed = speed;
Console.WriteLine("Car is braking!");
----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
Console.WriteLine("Car Honking!");
}
}
Console.WriteLine("Truck Honking!");
----------------------------------------------------------------------------------
namespace BankAccountManager.Models
public BankAccount()
Id = Guid.NewGuid();
CreatedDate = DateTime.UtcNow;
----------------------------------------------------------------------------------
using System.Collections.Generic;
using System.Linq;
namespace BankAccountManager.Models
accounts.Add(account);
if (account != null)
accounts.Remove(account);
return accounts;
----------------------------------------------------------------------------------
namespace BankAccountManager.Models
{
public class SavingsAccount : BankAccount
----------------------------------------------------------------------------------
namespace BankAccountManager.Models
public BankAccount()
Id = Guid.NewGuid();
CreatedDate = DateTime.UtcNow;
----------------------------------------------------------------------------------
using BankAccountManager.Models;
using Microsoft.AspNetCore.Mvc;
using System;
namespace BankAccountManager.Controllers
[ApiController]
[Route("api/[controller]")]
_bank = bank;
[HttpGet("accounts")]
return Ok(_bank.GetAccounts());
[HttpPost("accounts")]
public IActionResult AddAccount([FromBody] BankAccount account)
_bank.AddAccount(account);
[HttpDelete("accounts/{id}")]
_bank.RemoveAccount(id);
return NoContent();
----------------------------------------------------------------------------------
using BankAccountManager.Models;
builder.Services.AddSingleton<Bank>();
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
app.UseSwagger();
app.UseSwaggerUI();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
----------------------------------------------------------------------------------
"balance": 1000.00
----------------------------------------------------------------------------------
void Process();
----------------------------------------------------------------------------------
Balance += amount;
Balance -= amount;
----------------------------------------------------------------------------------
Id = Guid.NewGuid();
Balance = initialBalance;
~BankAccount()
}
----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
namespace BankAccountManager.Models
----------------------------------------------------------------------------------