0
0
C Sharp (C#)programming~30 mins

Multiple generic parameters in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Multiple Generic Parameters in C#
📖 Scenario: You are building a simple container class that can hold two different types of items together, like a box with two compartments.
🎯 Goal: Create a generic class with two type parameters and use it to store and display two different values.
📋 What You'll Learn
Create a generic class called Pair with two generic type parameters: T1 and T2.
Add two public fields: First of type T1 and Second of type T2.
Create a constructor that takes two parameters to initialize First and Second.
Create an instance of Pair with string and int types.
Print the values of First and Second.
💡 Why This Matters
🌍 Real World
Generic classes with multiple type parameters are useful when you want to group two related but different types of data together, like a key-value pair or a coordinate point.
💼 Career
Understanding multiple generic parameters helps in writing flexible and reusable code, which is important in software development jobs that require designing libraries, APIs, or data structures.
Progress0 / 4 steps
1
Create the generic class with two type parameters
Create a generic class called Pair with two generic type parameters T1 and T2. Inside the class, declare two public fields: First of type T1 and Second of type T2.
C Sharp (C#)
Need a hint?

Use public class Pair<T1, T2> to declare the class with two generic parameters.

2
Add a constructor to initialize the fields
Add a constructor to the Pair class that takes two parameters: first of type T1 and second of type T2. Inside the constructor, set the fields First and Second to these parameters.
C Sharp (C#)
Need a hint?

Constructor name must match the class name Pair. Assign parameters to fields inside the constructor.

3
Create an instance of the generic class
In the Main method, create an instance of Pair with string as T1 and int as T2. Name the variable myPair and initialize it with the values "apple" and 5.
C Sharp (C#)
Need a hint?

Use new Pair<string, int>("apple", 5) to create the instance.

4
Print the values of the generic fields
Add two Console.WriteLine statements in the Main method to print the values of myPair.First and myPair.Second.
C Sharp (C#)
Need a hint?

Use Console.WriteLine(myPair.First); and Console.WriteLine(myPair.Second); to print the values.