To Apply OOP principles in C# with design patterns for robust software architecture.
Table of contents
Open Table of contents
Introduction
This lab covers Object-Oriented Programming (OOP) concepts in C#, including encapsulation, inheritance, polymorphism, and abstraction [1].
Environment Setup
- VS Code with C# Dev Kit Extension
- .NET SDK (Latest Stable Version)
- Terminal/Command Prompt
File Structure
OOPLab/
│── Program.cs
│── Models/
│ ├── Person.cs
│ ├── Employee.cs
│── OOPLab.csproj
Steps
1. Create a New C# Console App
Open VS Code, then run:
dotnet new console -o OOPLab
cd OOPLab
code .
2. Implement Encapsulation (Models/Person.cs
)
namespace OOPLab.Models;
public class Person
{
private string name;
public string Name
{
get { return name; }
set { name = value.Length > 0 ? value : "Unknown"; }
}
public Person(string name) => Name = name;
public void Display() => Console.WriteLine($"Name: {Name}");
}
3. Implement Inheritance (Models/Employee.cs
)
namespace OOPLab.Models;
public class Employee : Person
{
public string Role { get; set; }
public Employee(string name, string role) : base(name) => Role = role;
public void ShowDetails() => Console.WriteLine($"Name: {Name}, Role: {Role}");
}
4. Implement Polymorphism (Program.cs
)
using OOPLab.Models;
class Program
{
static void Main()
{
Person p = new Person("Alice");
p.Display();
Employee e = new Employee("Bob", "Developer");
e.ShowDetails();
// Polymorphism: Using base class reference
Person poly = new Employee("Charlie", "Manager");
((Employee)poly).ShowDetails();
}
}
5. Run the Application
dotnet run
Additional Scopes
- Implement abstract classes and interfaces.
- Add method overriding and operator overloading.
- Use collections (List, Dictionary) with OOP.
References
[1] Microsoft Docs: C# OOP Fundamentals.
[2] .NET CLI Guide for Console Apps.