1713710977

Practical examples of object-oriented programming in C#.


Let's play around with object-oriented programming in Csharp, shall we? Here are five practical examples: ## 1. Modeling a car: ```csharp class Car { public string Brand { get; set; } public string Model { get; set; } public int Year { get; set; } public void Start() { Console.WriteLine("The car is started."); } public void Stop() { Console.WriteLine("The car is stopped."); } } // Usage: Car myCar = new Car(); myCar.Brand = "Toyota"; myCar.Model = "Corolla"; myCar.Year = 2020; myCar.Start(); ``` <br> --- ## <br>2. Bank account management: ```csharp class BankAccount { public string AccountNumber { get; set; } public decimal Balance { get; private set; } public void Deposit(decimal amount) { Balance += amount; } public void Withdraw(decimal amount) { if (amount <= Balance) { Balance -= amount; } else { Console.WriteLine("Insufficient balance."); } } } // Usage: BankAccount myAccount = new BankAccount(); myAccount.AccountNumber = "123456"; myAccount.Deposit(1000); myAccount.Withdraw(500); ``` <br> --- ## <br>3. Representation of employees: ```csharp class Employee { public string Name { get; set; } public string Position { get; set; } public decimal Salary { get; set; } } // Usage: Employee newEmployee = new Employee(); newEmployee.Name = "John"; newEmployee.Position = "Developer"; newEmployee.Salary = 3000; ``` <br> --- ## <br>4. Handling products in a sales system: ```csharp class Product { public string Name { get; set; } public decimal Price { get; set; } public int Stock { get; set; } } // Usage: Product newProduct = new Product(); newProduct.Name = "T-shirt"; newProduct.Price = 20; newProduct.Stock = 100; ``` <br> --- ## <br>5. Implementation of a game with classes for player and enemy: ```csharp class Character { public string Name { get; set; } public int HealthPoints { get; set; } public void Attack(Character target) { Console.WriteLine($"{Name} attacked {target.Name}!"); // Logic to calculate damage, etc. } } // Usage: Character player = new Character(); player.Name = "Hero"; player.HealthPoints = 100; Character enemy = new Character(); enemy.Name = "Villain"; enemy.HealthPoints = 80; player.Attack(enemy); ``` These examples demonstrate how you can use object-oriented programming in C# to model and interact with different types of objects in your programs. Participate by creating valuable programming content and sharing it with our community.

To comment this publication you need to be logged in.