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

Generic class declaration in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Generic class declaration
📖 Scenario: You are creating a simple container that can hold any type of item. This container will be a generic class so it can store different types without rewriting code.
🎯 Goal: Build a generic class called Box that can store one item of any type. Then create an instance of Box for an integer and store a number inside it.
📋 What You'll Learn
Create a generic class named Box with one type parameter T.
Add a public property Item of type T with get and set accessors.
Create an instance of Box for int type named intBox.
Set the Item property of intBox to the integer value 123.
Print the value of intBox.Item.
💡 Why This Matters
🌍 Real World
Generic classes let you write flexible code that works with many data types without repeating yourself.
💼 Career
Understanding generics is important for writing reusable and type-safe code in professional C# development.
Progress0 / 4 steps
1
Create the generic class Box
Write a generic class declaration named Box with one type parameter T. Inside it, declare a public property Item of type T with get and set accessors.
C Sharp (C#)
Need a hint?

Use public class Box<T> to declare the generic class. Then add a property Item of type T with get and set.

2
Create an instance of Box for integers
Create a variable named intBox and assign it a new instance of Box for the type int.
C Sharp (C#)
Need a hint?

Use Box<int> intBox = new Box<int>(); to create the instance.

3
Set the Item property of intBox
Assign the integer value 123 to the Item property of intBox.
C Sharp (C#)
Need a hint?

Use intBox.Item = 123; to store the number.

4
Print the value stored in intBox.Item
Write a Console.WriteLine statement to print the value of intBox.Item.
C Sharp (C#)
Need a hint?

Use Console.WriteLine(intBox.Item); inside a Main method to print the value.