Object-Oriented Programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code to manipulate that data. C# is a powerful object-oriented programming language, and understanding OOP principles is essential for effective C# development. Let's dive into the key concepts of OOP in C#:
1. Classes and Objects:
- Class: A class is a blueprint or template for creating objects. It defines the properties (attributes) and behaviors (methods) that objects of the class will have. public class Car { // Fields (attributes) public string Model; public string Color; // Methods (behaviors) public void Start() { Console.WriteLine("Car started."); } public void Stop() { Console.WriteLine("Car stopped."); } }
- Object: An object is an instance of a class. It represents a specific instance with its own set of data and behavior. Car myCar = new Car(); myCar.Model = "Toyota"; myCar.Color = "Blue"; myCar.Start();
2. Encapsulation:
- Encapsulation is the bundling of data (attributes) and methods (behaviors) that operate on the data into a single unit (class). It hides the internal state of an object and only exposes the necessary operations to interact with it.
- Access modifiers (
public
,private
,protected
,internal
,protected internal
) control the visibility and accessibility of class members. - Example:
- public class Circle { private double radius; public void SetRadius(double r) { if (r > 0) radius = r; } public double GetArea() { return Math.PI * radius * radius; } }
3. Inheritance:
- Inheritance is a mechanism where a new class (derived class) inherits properties and behaviors from an existing class (base class).
- The derived class can extend the functionality of the base class and override its methods.
- Example:
- public class Circle { private double radius; public void SetRadius(double r) { if (r > 0) radius = r; } public double GetArea() { return Math.PI * radius * radius; } }
4. Polymorphism:
- Polymorphism allows objects of different classes to be treated as objects of a common base class.
- It enables dynamic method invocation, where the method called is determined at runtime based on the actual type of the object.
- Example:
- Shape[] shapes = new Shape[] { new Circle(), new Rectangle() }; foreach (Shape shape in shapes) { Console.WriteLine("Area: " + shape.GetArea()); }
5. Abstraction:
- Abstraction focuses on hiding the implementation details of a class and only exposing the essential features.
- Abstract classes and interfaces are used to achieve abstraction in C#.
- Example:
- public abstract class Shape { public abstract double GetArea(); }
6. Access Modifiers:
- Access modifiers control the accessibility of classes, methods, and fields.
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 (project).protected internal
: Accessible within the same assembly or from derived classes.
7. Constructors and Destructors:
- Constructors are special methods used to initialize objects when they are created.
- Destructors (finalizers) are used to clean up resources before an object is destroyed.
- Example:
- public class Person { public string Name; // Constructor public Person(string name) { Name = name; } // Destructor (not commonly used in C#) ~Person() { Console.WriteLine("Person object destroyed."); } }
Let's create an example that demonstrates the use of object-oriented programming (OOP) concepts in C#. In this example, we'll create a simple banking system with classes representing customers, accounts, and transactions.
using System; using System.Collections.Generic; // Define the Customer class public class Customer { public int Id { get; set; } public string Name { get; set; } public Customer(int id, string name) { Id = id; Name = name; } } // Define the Account class public class Account { public int AccountNumber { get; } public Customer Owner { get; } public double Balance { get; private set; } public Account(int accountNumber, Customer owner, double initialBalance) { AccountNumber = accountNumber; Owner = owner; Balance = initialBalance; } public void Deposit(double amount) { if (amount > 0) { Balance += amount; Console.WriteLine($"Deposited {amount:C}. New balance: {Balance:C}"); } else { Console.WriteLine("Invalid deposit amount."); } } public void Withdraw(double amount) { if (amount > 0 && Balance >= amount) { Balance -= amount; Console.WriteLine($"Withdrawn {amount:C}. New balance: {Balance:C}"); } else { Console.WriteLine("Invalid withdrawal amount or insufficient balance."); } } } // Main class to demonstrate the banking system class Program { static void Main(string[] args) { // Create customers Customer customer1 = new Customer(1, "Alice"); Customer customer2 = new Customer(2, "Bob"); // Create accounts for customers Account account1 = new Account(1001, customer1, 1000); Account account2 = new Account(1002, customer2, 2000); // Deposit and withdraw from accounts account1.Deposit(500); account2.Withdraw(1000); // Display account information Console.WriteLine($"Account {account1.AccountNumber} owner: {account1.Owner.Name}, Balance: {account1.Balance:C}"); Console.WriteLine($"Account {account2.AccountNumber} owner: {account2.Owner.Name}, Balance: {account2.Balance:C}"); } }
In this example:
- We have two classes:
Customer
andAccount
. Customer
class represents bank customers with properties for ID and name.Account
class represents bank accounts with properties for account number, owner (aCustomer
object), and balance.Account
class has methods for depositing and withdrawing money from the account.- In the
Main
method, we create instances ofCustomer
andAccount
, perform deposit and withdrawal operations, and display account information.
This example demonstrates encapsulation, where the data (properties) and behavior (methods) of objects are encapsulated within their respective classes, and objects interact with each other to perform actions.
Understanding and applying these OOP principles will help you write modular, maintainable, and scalable code in C#. Practice implementing these concepts in your projects to solidify your understanding.
0 Comments