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

Generic class declaration in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a generic class in C#?
A generic class is a class that can work with any data type. It uses a placeholder (type parameter) that is replaced with a real type when the class is used.
Click to reveal answer
beginner
How do you declare a generic class named <code>Box</code> with one type parameter <code>T</code>?
You write: <pre>public class Box&lt;T&gt; { }</pre> This means <code>Box</code> can hold any type <code>T</code> you choose later.
Click to reveal answer
beginner
Why use generic classes instead of normal classes?
Generic classes let you write flexible and reusable code. You avoid repeating the same code for different data types and get type safety without casting.
Click to reveal answer
beginner
What does <code>T</code> represent in <code>class Box&lt;T&gt;</code>?
T is a type parameter. It is a placeholder for a real data type that you specify when creating an object of the class.
Click to reveal answer
beginner
How do you create an instance of a generic class Box<T> for type int?
You write:
Box<int> intBox = new Box<int>();
This creates a Box that works with integers.
Click to reveal answer
What symbol is used to declare a generic type parameter in a class?
A<>
B()
C[]
D{}
Which of these is a correct generic class declaration?
Apublic class List{T} { }
Bpublic class List(T) { }
Cpublic class List[T] { }
Dpublic class List<T> { }
What does the T in class Box<T> stand for?
AA specific type like int
BA placeholder for any type
CA method name
DA variable name
Why are generic classes useful?
AThey allow code reuse for different data types
BThey make code slower
CThey only work with strings
DThey remove type safety
How do you create an object of a generic class Box<T> for strings?
ABox myBox = new Box();
BBox<T> myBox = new Box<T>();
CBox<string> myBox = new Box<string>();
DBox<string> myBox = Box<string>();
Explain what a generic class is and why it is useful in C#.
Think about how you can write one class to work with many types.
You got /4 concepts.
    Describe how to declare and create an instance of a generic class with an example.
    Use the example of a class named Box with type T.
    You got /4 concepts.