Let's think about this for a second
This exercise set is designed to combine and practice the OOP concepts (classes, inheritance, polymorphism), collections (List, Dictionary), and LINQ covered in the Intermediate and Advanced chapters. These tasks are tougher than Practice Exercises: Fundamentals — you'll need to design your own classes and query collections with LINQ. Once you can get through this level, you'll feel a lot more confident tackling mini-projects. Build and run each task as its own separate console app project.
Exercises
(1) Write an Animal base class with a Name property and a virtual MakeSound() method, then create two subclasses, Dog and Cat, that override MakeSound(). Add Dog and Cat objects to a List<Animal>, loop through it calling MakeSound(), and confirm that polymorphism is working as expected. (2) Set up a Dictionary<string, int> with product name as the key and stock quantity as the value, then use LINQ's Where() to find and print all products with stock below 10. (3) Write a Student class (Name, List<int> Scores), calculate each student's average score in a List<Student> using LINQ's Average(), and use OrderByDescending() to find the student with the highest average.
Code Example
// Task 1 starter
class Animal
{
public string Name { get; set; }
public virtual void MakeSound()
{
Console.WriteLine($"{Name} makes a sound");
}
}
class Dog : Animal
{
public override void MakeSound() => Console.WriteLine($"{Name} says Woof!");
}
class Cat : Animal
{
public override void MakeSound() => Console.WriteLine($"{Name} says Meow!");
}
// Task 2 starter
Dictionary<string, int> stock = new Dictionary<string, int>
{
{ "Pen", 25 }, { "Notebook", 8 }, { "Eraser", 3 }, { "Ruler", 40 }
};
var lowStock = stock.Where(s => s.Value < 10);
foreach (var item in lowStock)
Console.WriteLine($"{item.Key}: {item.Value}");
// Task 3 starter
class Student
{
public string Name { get; set; }
public List<int> Scores { get; set; }
}
List<Student> students = new List<Student>
{
new Student { Name = "Aye", Scores = new List<int> { 80, 90, 70 } },
new Student { Name = "Min", Scores = new List<int> { 60, 75, 65 } }
};
// students.OrderByDescending(s => s.Scores.Average()) သုံးပြီး top student ကို ရှာပါAll three tasks will produce the expected output: the correct Dog/Cat sounds appearing, the list of low-stock products, and the student with the highest average score identified.5-Minute Challenge
Add a Bird class to Task 1, override MakeSound(), include a Bird object in the List<Animal>, and re-run the loop to see it in action (5 minutes).
A Quick Heads-Up
Remember that polymorphism only works when you mark the base class method virtual AND mark the derived class method override — you need both.