Meet The Author

I'm Ethan Jackson, An 25 years old blogger Currently living in London, United Kingdom. I'm a Skilled Blogger, Part Time web Developer And Creating new things as a web Designer.

author

Minimal APIs Cheatsheet (in ASP.NET Core)

Leave a Comment

Minimal APIs were introduced in .NET 6 to simplify the creation of small, fast, and lightweight web APIs. They allow developers to express API logic with minimal code and configuration, without having controllers or properties like in typical ASP.NET MVC. They are best used when constructing small services, microservices, or proof-of-concept systems.

1. Create a New Minimal API Project

To get started

dotnet new web -n MinimalApiDemo
  • This template sets up a basic minimal API.
  • No controllers or Views folder.
2. Basic Program.cs Structure
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.Run();
  • MapGet defines a GET endpoint.
  • Everything is written in Program.cs.
3. MapGet() – Handle GET Requests
app.MapGet("/hello", () => "Hi there!");
  • Used to return data or simple messages.
  • Can return strings, objects, or JSON.
4. MapPost() – Handle POST Requests
app.MapPost("/add", (int x, int y) => x + y);
  • Accepts parameters directly from query or body.
  • Ideal for submitting data.
5. MapPut() – Handle PUT Requests
app.MapPut("/update", (int id, string name) => $"Updated {id} to {name}");
  • Used to update existing resources.

6. MapDelete() – Handle DELETE Requests
app.MapDelete("/delete/{id}", (int id) => $"Deleted item {id}");
  • Deletes a resource based on the ID.

7. Return JSON Response
app.MapGet("/user", () => new { Name = "John", Age = 25 });
  • Automatically serializes object to JSON.
  • No need for extra configuration.
8. Reading From Query Strings
app.MapGet("/greet", (string name) => $"Hello, {name}!");
  • Pass like /greet?name=Diksha.

9. Reading From Route Parameters
app.MapGet("/product/{id}", (int id) => $"Product ID: {id}");
  • Route parameters are defined inside {}.

10. Read JSON Body in POST
app.MapPost("/person", (Person person) =>
{
    return $"Name: {person.Name}, Age: {person.Age}";
});

record Person(string Name, int Age);
  • Automatically binds the JSON request body to an object.
  • Use record or class.
11. Dependency Injection (DI)

Register service

builder.Services.AddSingleton<MyService>();

Use it in the route

app.MapGet("/info", (MyService svc) => svc.GetInfo());
  • Supports constructor-less DI in lambda.

12. Validation Example
app.MapPost("/validate", (User user) =>
{
    if (string.IsNullOrWhiteSpace(user.Email))
        return Results.BadRequest("Email is required");

    return Results.Ok("Valid User");
});

record User(string Email);
  • Manual validation can be added easily.

13. Using Results Object
app.MapGet("/status", () => Results.Ok("Working"));
app.MapGet("/fail", () => Results.BadRequest("Something went wrong"));
  • Explicit control over HTTP response type and status.

14. Grouping Routes
var userGroup = app.MapGroup("/users");

userGroup.MapGet("/", () => "All users");
userGroup.MapPost("/", (User u) => $"User {u.Email} added");
  • Helps organize related endpoints under a common path.

15. Middleware Usage
app.Use(async (context, next) =>
{
    Console.WriteLine("Request coming in");
    await next();
    Console.WriteLine("Response going out");
});
  • Minimal APIs support middlewares like normal APIs.

16. Enable Swagger (OpenAPI)

Add services

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

Use Swagger UI

app.UseSwagger();
app.UseSwaggerUI();
  • Helps with testing and documentation.

17. Route Constraints
app.MapGet("/item/{id:int}", (int id) => $"Item ID: {id}");
  • :int ensures only integer is accepted.

18. Allow CORS
builder.Services.AddCors();

app.UseCors(policy => policy.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
  • Enables cross-origin API calls.

if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
  • Add environment-specific behaviors.

20. Error Handling
app.UseExceptionHandler("/error");

app.Map("/error", () => Results.Problem("Unexpected error occurred"));
  • Define a global error route.

21. Run on Custom URL/Port

Update launchSettings.json or in code:

builder.WebHost.UseUrls("http://localhost:5001");
22. Route Prefix with [MapGroup] for Versioning
var v1 = app.MapGroup("/api/v1");

v1.MapGet("/products", () => "v1 products");
  • Helps version your API easily (/api/v1/products).

23. Use Authorization
builder.Services.AddAuthorization();
app.UseAuthorization();

app.MapGet("/secure", () => "Secure Data")
   .RequireAuthorization();
  • Supports role-based or policy-based authorization.

24. Async Endpoints
app.MapGet("/delay", async () =>
{
    await Task.Delay(1000);
    return "Done after delay";
});
  • All endpoints can be asynchronous using async/await.

25. Binding From Headers / Claims
app.MapGet("/agent", (HttpRequest req) =>
{
    var userAgent = req.Headers["User-Agent"];
    return $"Your agent: {userAgent}";
});
  • Use HttpRequest or HttpContext to access headers, claims, cookies, etc.

26. Custom Response Codes
app.MapGet("/notfound", () => Results.StatusCode(404));
  • Fine-grained control over HTTP response codes.

27. Conditional Endpoints (MapWhen)
app.MapWhen(ctx => ctx.Request.Path.StartsWithSegments("/admin"), appBuilder =>
{
    appBuilder.Run(async ctx => await ctx.Response.WriteAsync("Admin section"));
});
  • Handle advanced routing logic manually.

28. Bind Form Data
app.MapPost("/upload", async (HttpRequest req) =>
{
    var form = await req.ReadFormAsync();
    var file = form.Files["file"];
    return $"Uploaded: {file?.FileName}";
});
  • Useful for uploading files or handling multipart/form-data.

29. Handle Query, Route, and Body Together
app.MapPost("/mixed/{id}", (int id, string name, MyData data) =>
{
    return $"ID: {id}, Name: {name}, Data: {data.Value}";
});

record MyData(string Value);
  • You can mix route, query, and body parameters.

Comparison: Minimal APIs vs Traditional RESTful APIs (Controllers)
Feature Minimal APIs RESTful APIs (Controllers)
Setup Very low setup, all in Program.cs Needs controllers, attributes, and routing setup
Performance Slightly better (fewer layers) Slightly heavier due to abstraction layers
Best For Small services, microservices, and quick APIs Large-scale apps with many endpoints
Testability Less structured, harder to unit test Easier to test with controllers/services
Routing Code-based (inline) Attribute routing or convention-based
Dependency Injection Direct in lambda Via constructor injection in controllers
Maintainability (Large apps) Harder to scale/organize Better separation of concerns
Swagger Support Fully supported Fully supported
Custom Filters / Middleware Limited (no filters, but use middleware) Full support (filters, middleware, etc.)
Validation (FluentValidation, etc.) Manual or via packages Built-in integration via ModelState
Extensibility Limited to what's in lambdas/middleware Highly extensible (Filters, Bindings, etc.)

When to Use What?
Use Case Recommendation
Quick prototype or POC Minimal API
Microservices / serverless Minimal API
Full-blown business app RESTful API (Controllers)
App needing filters/attributes RESTful API
Highly structured/maintainable code RESTful API

Conclusion
Minimal APIs are a powerful tool for quickly building web APIs with clean and minimal code. They reduce boilerplate and work great for microservices or simple services. However, RESTful APIs with controllers continue to provide greater structure and long-term scalability for complex systems.

Use Minimal APIs when you want speed and simplicity, but switch to RESTful APIs when you need organization, structure, testability, or layered architecture. 

Windows Hosting Recommendation

HostForLIFE.eu receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 10.0 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More

.NET Core Dependency Injection with IServiceCollection

Leave a Comment

Modern applications may easily manage dependencies thanks to.NET Core's built-in support for Dependency Injection (DI), a design pattern that facilitates the creation of loosely connected code. Using the IServiceCollection interface, we will examine how DI functions in.NET Core in this post and go over a basic example. 

What Is Dependency Injection?

Dependency Injection is a technique where an object receives its dependencies from an external source rather than creating them itself. This makes the application easier to maintain, test, and scale.

Key Components in .NET Core DI

  • IServiceCollection – Used to register dependencies (services).
  • ServiceProvider – Used to resolve dependencies.
  • Service Lifetimes
    • Singleton: One instance for the application lifetime.
    • Scoped: One instance per request.
    • Transient: A new instance every time.

Example. Setting Up DI in a .NET Core Console Application

Let’s create a simple console app that demonstrates DI.

Step 1. Define Interfaces and Implementations

// IGreeter.cs
public interface IGreeter
{
    void Greet(string name);
}
// ConsoleGreeter.cs
public class ConsoleGreeter : IGreeter
{
    public void Greet(string name)
    {
        Console.WriteLine($"Hello, {name}!");
    }
}

Step 2. Set Up DI with IServiceCollection

// Program.cs
using Microsoft.Extensions.DependencyInjection;
using System;

class Program
{
    static void Main(string[] args)
    {
        // Step 1: Create a new service collection
        var serviceCollection = new ServiceCollection();

        // Step 2: Register services
        serviceCollection.AddTransient<IGreeter, ConsoleGreeter>();

        // Step 3: Build the service provider
        var serviceProvider = serviceCollection.BuildServiceProvider();

        // Step 4: Resolve and use the service
        var greeter = serviceProvider.GetRequiredService<IGreeter>();
        greeter.Greet("Alice");
    }
}

Explanation

  • AddTransient<IGreeter, ConsoleGreeter>(): Registers ConsoleGreeter as the implementation for IGreeter. A new instance is created every time it’s requested.
  • BuildServiceProvider(): Compiles the service registrations into a container that can resolve services.
  • GetRequiredService<IGreeter>(): Requests an instance of IGreeter. The DI container automatically injects the correct implementation.

When to Use Which Lifetime?

Lifetime Use When...
Singleton Service should be shared for the app lifetime
Scoped Per web request (mostly in ASP.NET Core apps)
Transient Lightweight, stateless services

Bonus: Use DI in ASP.NET Core

In ASP.NET Core, you don’t need to manually build the ServiceProvider. Just use ConfigureServices in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IGreeter, ConsoleGreeter>();
}

Then, inject via the constructor:

public class HomeController : Controller
{
    private readonly IGreeter _greeter;

    public HomeController(IGreeter greeter)
    {
        _greeter = greeter;
    }

    public IActionResult Index()
    {
        _greeter.Greet("User");
        return View();
    }
}
Conclusion

Dependency Injection in .NET Core is simple and powerful. Using IServiceCollection, you can register and manage dependencies with different lifetimes to keep your code clean and maintainable. Whether you're building a console app or a large web application, understanding and applying DI is a must-have skill in .NET Core development.

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 10.0, ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More

Real-World Example of CRUD Operations in ASP.NET Core Using Entity Framework

Leave a Comment

You want to manage Customer records with typical operations:

  • Create customer records

  • Get all customers or by ID

  • Update customer details

  • Delete customer records

Step-by-step implementation

1. Create Project

dotnet new webapi -n CustomerServiceApi
cd CustomerServiceApi

2. Define Customer Model

Create Models/Customer.cs

namespace CustomerServiceApi.Models
{
    public class Customer
    {
        public int Id { get; set; }
        public string FullName { get; set; } = string.Empty;
        public string Email { get; set; } = string.Empty;
        public string PhoneNumber { get; set; } = string.Empty;
        public DateTime RegisteredAt { get; set; } = DateTime.UtcNow;
    }
}

3. Setup DbContext

Create Data/AppDbContext.cs

using Microsoft.EntityFrameworkCore;
using CustomerServiceApi.Models;

namespace CustomerServiceApi.Data
{
    public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) {}

        public DbSet<Customer> Customers { get; set; }
    }
}

4. Configure EF Core and Services in Program.cs

using CustomerServiceApi.Data;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.Run();

Add connection string in appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Database=CustomerServiceDb;Trusted_Connection=True;TrustServerCertificate=True;"
  }
}

5. Create CustomersController

Create Controllers/CustomersController.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using CustomerServiceApi.Data;
using CustomerServiceApi.Models;

namespace CustomerServiceApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class CustomersController : ControllerBase
    {
        private readonly AppDbContext _context;

        public CustomersController(AppDbContext context)
        {
            _context = context;
        }

        // GET: api/customers
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Customer>>> GetCustomers()
        {
            return await _context.Customers.ToListAsync();
        }

        // GET: api/customers/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Customer>> GetCustomer(int id)
        {
            var customer = await _context.Customers.FindAsync(id);
            if (customer == null) return NotFound();
            return customer;
        }

        // POST: api/customers
        [HttpPost]
        public async Task<ActionResult<Customer>> CreateCustomer(Customer customer)
        {
            _context.Customers.Add(customer);
            await _context.SaveChangesAsync();
            return CreatedAtAction(nameof(GetCustomer), new { id = customer.Id }, customer);
        }

        // PUT: api/customers/5
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateCustomer(int id, Customer customer)
        {
            if (id != customer.Id) return BadRequest();

            _context.Entry(customer).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!_context.Customers.Any(c => c.Id == id))
                    return NotFound();
                else throw;
            }

            return NoContent();
        }

        // DELETE: api/customers/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteCustomer(int id)
        {
            var customer = await _context.Customers.FindAsync(id);
            if (customer == null) return NotFound();

            _context.Customers.Remove(customer);
            await _context.SaveChangesAsync();

            return NoContent();
        }
    }
}

6. Run EF Core Migration

Install EF CLI if needed

dotnet tool install --global dotnet-ef

Create and apply migration

dotnet ef migrations add InitialCreate
dotnet ef database update

7. Run and Test

dotnet run

Go to: https://localhost:5001/swagger

Test your Customer API endpoints with Swagger UI:

  • GET /api/customers

  • POST /api/customers

  • GET /api/customers/{id}

  • PUT /api/customers/{id}

  • DELETE /api/customers/{id}

Summary

You now have a real-time Customer Service REST API managing customer records with full CRUD using Entity Framework Core in ASP.NET Core. This can be extended with authentication, paging, validation, etc.

If you want, I can help with those next! Would you like that?

Windows Hosting Recommendation

HostForLIFE.eu receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 9.0, ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More

Selecting the Best ASP.NET Core 10.0 Hosting in Europe

Leave a Comment
Based on its useful features and easy to use, many developer need powerful web hosting to support their ASP.NET Core 10.0 site well. Because of that, we will inform you the Best ASP.NET Core 10.0 Hosting in Europe provider with affordable price and high quality support. After reviewed 20+ ASP.NET Core 10.0 Hosting in Europe, we had come out with the best ASP.NET Core 10.0 Hosting in Europe, control libraries, databases, technical support, and web hosting price. 


ASP.NET Core is a free and open-source web framework, and higher performance than ASP.NET, developed by Microsoft and the community. It is a modular framework that runs on both the full .NET Framework, on Windows, and the cross-platform .NET Core. Despite being a new framework, built on a new web stack, it does have a high degree of concept compatibility with ASP.NET MVC. ASP.NET Core applications supports side by side versioning in which different applications, running on the same machine, can target different versions of ASP.NET Core. This is not possible with previous versions of ASP.NET.

Best & Cheap ASP.NET Core 10.0 Hosting in Europe

Our Best, Cheap ASP.NET Core 10.0 Hosting in Europe Recommendation goes to HostForLIFEASP.NET, a leading web hosts who is well-known for offering high quality Windows hosting from shared hosting

http://hostforlifeasp.net/European-ASPNET-Core-2-Hosting

Founded in United Kingdom, and with years’ expansion, HostForLIFEASP.NET has grown into one of top 10 ASP.NET Core 10.0 Hosting in Europe hosting providers for offers reliable and affordable web hosting services on Windows platforms. HostForLIFEASP.NET a worldwide provider of hosting support the latest release of Microsoft's widely-used ASP.NET Core 10.0 Hosting in Europe. You can take advantage of the powerful ASP.NET Core 10.0 Hosting in Europe technology in all Windows Shared Hosting, Windows Reseller Hosting and Windows Cloud Hosting Packages. 

SALE 35% OFF NOW!

HostForLIFEASP.NET Budget Friendly Price – The service includes 4 packages called as HostForLIFE Basic, Budget, Economy and Business with the price starting at Є2.97/mo.


  • 30 Days Money Back Guarantee – This means webmasters are allowed to get a refund if they cancel the services because of dissatisfaction within the first 30 days.
  • Satisfactory Uptime – HostForLIFEASP.NET employs state-of-the-art data centers and advanced technologies guaranteeing 99.99% uptime shown by the following chart.

HostForLIFE ASP.NET Core 10.0 Hosting in Europe Performance

HostForLIFEASP.NET ASP.NET Core 10.0 web host reliability is absolutely outstanding compared to other comprehensive web hosting companies. HostForLIFEASP.NET is managed by a sophisticated team with lots of Windows server experts. With the correct IIS, website and file system permission configuration, the security of the hosting websites is well isolated. That means, when one website is hacked by improper code, it’s rare opportunity for other websites be affected.

Technical Support

As introduced above, HostForLIFEASP.NET has an experienced team on supporting ASP.NET and ASP.NET Core 10.0 Hosting in Europe. All of their technical support staffs are kindly, sophisticated and knowledgeable on either Windows platform or SQL Server 2016 databases. HostForLIFEASP.NET provides 24/7 email and ticket system support mainly. Based on our testing, the average of the first response is about 30 minutes, and it could be faster in working time. HostForLIFEASP.NET guarantees to respond each support ticket in 12 hours.

HostForLIFE is Best Option for ASP.NET Core 10.0 Hosting in Europe

Frankly speaking, HostForLIFE is best option to host your ASP.NET Core 10.0 Hosting in Europe. You just need to spend €2.97/month to host your site with them and you can install the latest ASP.NET Core 10.0 via their Plesk control panel. We would highly recommend them as your ASP.NET Core 10.0 Hosting in Europe.

http://hostforlifeasp.net/European-ASPNET-Core-2-Hosting

Read More

ASP.NET Tutorial : Object Oriented Programming Concepts in C# (2025)

Leave a Comment

A fundamental paradigm in contemporary software development, object-oriented programming (OOP) arranges software design around data or objects rather than just functions and logic. OOP is a major component of C#, a flexible and strong programming language created by Microsoft that is ideal for creating scalable, maintainable, and reliable programs.

In 2025, C# continues to evolve with modern language features while keeping its core OOP principles intact. This article explores the fundamental OOP concepts in C# and highlights how they integrate with the latest language enhancements.

What is Object-Oriented Programming?

OOP is a programming model based on the concept of “objects,” which are instances of classes. Objects combine data (fields or properties) and behaviors (methods) into a single unit. This model facilitates the structuring of programs that are easier to manage, extend, and reuse.

Four Core OOP Principles

  1. Encapsulation
  2. Inheritance
  3. Polymorphism
  4. Abstraction
Object-Oriented Concepts in C#

1. Classes and Objects

  • Class: A blueprint or template that defines properties, methods, events, and other members.
  • Object: An instance of a class representing a concrete entity in memory.
    public class Car
    {
        public string Make { get; set; }
        public string Model { get; set; }
    
        public void Drive()
        {
            Console.WriteLine("Driving the car");
        }
    }
    // Creating an object of Car
    Car myCar = new Car
    {
        Make = "Tesla",
        Model = "Model S"
    };
    myCar.Drive();

In C#, classes define both data and behavior. Objects are created from these classes to perform real tasks.

2. Encapsulation

Encapsulation refers to bundling data and methods that operate on that data within a class and restricting direct access to some of the object’s components.

Access Modifiers: public, private, protected, internal, and protected internal control visibility.

public class BankAccount
{
    private decimal balance; // Private field, not accessible outside class
    public decimal Balance
    {
        get { return balance; }
        private set { balance = value; } // Only the class can set balance
    }
    public void Deposit(decimal amount)
    {
        if (amount > 0)
        {
            Balance += amount;
        }
    }
}

Encapsulation enhances security and protects object integrity by controlling how data is accessed and modified.

3. Inheritance

  • Inheritance allows a new class (derived or child class) to inherit fields, properties, and methods from an existing class (base or parent class). This promotes code reuse.
    public class Animal
    {
        public void Eat() => Console.WriteLine("Eating");
    }
    
    public class Dog : Animal
    {
        public void Bark() => Console.WriteLine("Barking");
    }
    
    Dog dog = new Dog();
    dog.Eat();  // Inherited from Animal
    dog.Bark();
  • C# supports single inheritance (a class can inherit only from one base class).
  • Multiple inheritance of interfaces is supported, providing flexibility.

4. Polymorphism

Polymorphism allows methods to have multiple forms. In C#, this is primarily achieved via.

  • Method Overloading: Same method name, different parameters.
  • Method Overriding: A derived class provides a specific implementation of a base class method using the virtual and override keywords.
  • Interface Implementation: Different classes implement the same interface in different ways.
    public class Shape
    {
        public virtual void Draw()
        {
            Console.WriteLine("Drawing Shape");
        }
    }
    public class Circle : Shape
    {
        public override void Draw()
        {
            Console.WriteLine("Drawing Circle");
        }
    }
    Shape shape = new Circle();
    shape.Draw();  // Output: Drawing Circle (runtime polymorphism)

5. Abstraction

Abstraction hides the complex implementation details and shows only the necessary features of an object. C# achieves abstraction via.

  • Abstract Classes: These cannot be instantiated and can have abstract methods that derived classes must implement.
  • Interfaces: Define a contract without implementation.
    public abstract class Vehicle
    {
        public abstract void Start();
    }
    public class Bike : Vehicle
    {
        public override void Start()
        {
            Console.WriteLine("Bike started");
        }
    }

New and Modern OOP Features in C# (2025)

C# has evolved significantly, with newer versions introducing features that complement OOP.

Records and Immutable Types

Introduced in C# 9 and enhanced since records are reference types with value-based equality and immutability by default.

public record Person(string FirstName, string LastName);

Records emphasize immutability, a trend in modern programming, which helps facilitate safer multi-threaded and functional-style programming.

Pattern Matching

Pattern matching enables more precise and concise handling of objects based on their type or structure, which is particularly helpful in polymorphic scenarios.

if (obj is Circle c)
{
    c.Draw();
}

Default Interface Methods

Interfaces can now contain default implementations, enabling interface evolution without breaking existing implementations.

public interface ILogger
{
    void Log(string message);
    void LogError(string error) => Log($"Error: {error}");
}

Best Practices for OOP in C# (2025)

  • Favor Composition over Inheritance: Use object composition to build flexible systems.
  • Use Interfaces to Define Contracts: Promotes loose coupling.
  • Leverage Encapsulation for Data Protection: Use appropriate access modifiers.
  • Prefer Immutable Objects: Utilize record types and readonly fields.
  • Keep Methods Small and Focused: Single responsibility principle (SRP).
  • Utilize Modern Language Features: Such as pattern matching and default interface methods for cleaner code.
Conclusion

Object-oriented programming remains a cornerstone of C# programming in 2025, enriched by modern features that make it more expressive, safer, and easier to maintain. Understanding OOP concepts, including encapsulation, inheritance, polymorphism, and abstraction, alongside recent language enhancements, empowers developers to build scalable, maintainable, and performant applications.

Windows Hosting Recommendation

HostForLIFE.eu receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 10.0, ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More
Previous PostOlder Posts Home