OOP Concepts in C# and .
NET Core REST APIs
1. Introduction to OOP in C#
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of 'objects'.
C# supports OOP with features like classes, objects, inheritance, polymorphism, abstraction, and
encapsulation.
Key advantages of OOP:
- Reusability
- Scalability
- Maintainability
- Data Security
OOP Concepts in C# and .NET Core REST APIs
2. Encapsulation
Encapsulation is the concept of wrapping data and methods that work on data within one unit.
Example:
class Person {
private string name;
public string Name {
get { return name; }
set { name = value; }
}
OOP Concepts in C# and .NET Core REST APIs
3. Inheritance
Inheritance allows a class to inherit methods and properties from another class.
Example:
class Animal {
public void Eat() => [Link]("Eating");
class Dog : Animal {
public void Bark() => [Link]("Barking");
}
OOP Concepts in C# and .NET Core REST APIs
4. Polymorphism and Abstraction
Polymorphism means having many forms. It allows methods to do different things based on the
object.
Example:
class Shape {
public virtual void Draw() => [Link]("Drawing Shape");
class Circle : Shape {
public override void Draw() => [Link]("Drawing Circle");
Abstraction hides implementation details and shows only functionality.
Example:
abstract class Vehicle {
public abstract void Start();
class Car : Vehicle {
public override void Start() => [Link]("Car started");
}
OOP Concepts in C# and .NET Core REST APIs
5. Interfaces and OOP in Practice
Interfaces define a contract that classes must follow.
Example:
interface ILogger {
void Log(string message);
class FileLogger : ILogger {
public void Log(string message) {
[Link]("File Log: " + message);
OOP in practice makes code more modular and easier to manage in large applications.
OOP Concepts in C# and .NET Core REST APIs
6. .NET Core REST APIs
.NET Core provides a framework for building RESTful services using [Link] Core.
Steps to create a REST API:
1. Create a new Web API project
2. Define models
3. Create controllers
4. Add routing and middleware
Example Controller:
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase {
[HttpGet]
public IActionResult GetAll() => Ok(new[] { "Apple", "Banana" });
.NET Core supports dependency injection, middleware, and OpenAPI (Swagger) integration
out-of-the-box.