A repository of exercises to support the training.
In this exercise module, we dive into the world of generics to enhance code flexibility and reusability. You'll be working on a space-themed exercise where you'll create a generic class, method, and overload to process, store, and manipulate data related to celestial objects.
Your first task is to create a generic class that can store and manipulate data about various celestial objects, like stars, planets, or asteroids.
Instructions:
CosmicData<T>
that can store data of any type.Class Example:
class CosmicData<T>
{
private List<T> data = [];
// Method to add data
// Method to retrieve data
// Method to display all data
}
Expected Outcome:
Now, extend your work by creating a generic method that performs a calculation on the cosmic data. For example, calculating the average mass of a group of planets.
Instructions:
CalculateAverage<T>
that works for any numerical type (e.g., int
, double
).int[] planetMasses = { 100, 200, 300 };
double averageMass = CosmicCalculator.CalculateAverage(planetMasses);
Console.WriteLine($"Average Planet Mass: {averageMass}");
Expected Outcome:
Finally, you'll explore how to overload a generic method to handle specific cases, such as when you're dealing with a particular type of data (e.g., star names).
Instructions:
AddData
method in the CosmicData<T>
class to handle a special case for string
types.CosmicData<string> starNames = new CosmicData<string>();
starNames.AddData("Sirius");
starNames.AddData("Betelgeuse");
starNames.DisplayData();
Expected Outcome:
May your coding journey be filled with fun and discovery!