Generic classes let you create flexible blueprints that work with any type of data. This helps you reuse code without repeating it for each data type.
Generic class declaration in C Sharp (C#)
class ClassName<T> { // Members using T }
T is a placeholder for any type you specify when using the class.
You can use any name instead of T, but T is a common convention.
Box that can hold any type of content.class Box<T> { public T Content; }
class Pair<T1, T2> { public T1 First; public T2 Second; }
T must be a reference type (class).class Storage<T> where T : class { public T Item; }
This program creates a generic class Box that can hold any type. We make one box for integers and one for strings, then print their contents.
using System; class Box<T> { public T Content; public void ShowContent() { Console.WriteLine($"Content: {Content}"); } } class Program { static void Main() { Box<int> intBox = new Box<int>(); intBox.Content = 123; intBox.ShowContent(); Box<string> strBox = new Box<string>(); strBox.Content = "Hello"; strBox.ShowContent(); } }
Generic classes help avoid errors by checking types at compile time.
You can add constraints to limit what types can be used with your generic class.
Use descriptive names for type parameters if you have many, like TKey and TValue.
Generic classes let you write one class that works with any data type.
Use angle brackets <> to declare type parameters.
They improve code reuse and type safety.
Practice
What is the main purpose of declaring a generic class in C# using <T>?
Solution
Step 1: Understand generic class purpose
Generic classes use type parameters to work with any data type, improving code reuse and safety.Step 2: Compare options with generic concept
Only To allow the class to work with any data type safely correctly states that generics allow safe use with any data type.Final Answer:
To allow the class to work with any data type safely -> Option AQuick Check:
Generic class purpose = safe, reusable code [OK]
- Thinking generics restrict to one type
- Believing generics improve speed by skipping checks
- Confusing generics with automatic class creation
Which of the following is the correct syntax to declare a generic class named Box with one type parameter?
?
Solution
Step 1: Recall generic class syntax
Generic classes use angle brackets with type parameters:class ClassName<T>.Step 2: Check each option
public class Box<T> { } matches correct syntax. Options A, B, and D have syntax errors or wrong symbols.Final Answer:
public class Box<T> { } -> Option BQuick Check:
Generic syntax = class Name<T> [OK]
- Using parentheses instead of angle brackets
- Adding parentheses after class name
- Using square brackets instead of angle brackets
What will be the output of the following C# code?
public class Container<T> {
public T Value;
public Container(T value) { Value = value; }
public override string ToString() => $"Value: {Value}";
}
var intBox = new Container<int>(10);
var strBox = new Container<string>("Hello");
Console.WriteLine(intBox);
Console.WriteLine(strBox);Solution
Step 1: Understand class behavior
The class stores a value of type T and overrides ToString() to print "Value: {Value}".Step 2: Trace output of Console.WriteLine
intBox.ToString() returns "Value: 10" and strBox.ToString() returns "Value: Hello".Final Answer:
Value: 10 Value: Hello -> Option AQuick Check:
ToString override prints value with prefix [OK]
- Expecting variable names instead of values
- Ignoring ToString() override
- Thinking type constraints are required here
Identify the error in this generic class declaration and fix it:
public class Pair<T, U>
{
public T First;
public U Second;
public Pair(T first, U second)
{
First = first;
Second = second;
}
}
var p = new Pair<string>(5, "test");Solution
Step 1: Check instance creation syntax
Generic classes require type arguments when instantiated unless using C# 7.1+ with target-typed new.Step 2: Identify missing type arguments
The code usesnew Pair<string>(5, "test")without specifying<int, string>, causing error.Final Answer:
Missing type arguments when creating instance: use new Pair<int, string>(5, "test") -> Option CQuick Check:
Generic instantiation needs type args [OK]
- Omitting type arguments on new
- Thinking generic classes can't have multiple parameters
- Changing constructor parameter order unnecessarily
You want to create a generic class Cache<TKey, TValue> that stores key-value pairs and only allows reference types for TValue. Which declaration is correct?
Solution
Step 1: Understand type constraints
To restrict a generic type to reference types, usewhere Type : class.Step 2: Apply constraint to TValue
The question requiresTValueto be a reference type, so constraint applies toTValue.Final Answer:
public class Cache<TKey, TValue> where TValue : class { } -> Option DQuick Check:
Reference type constraint = where TValue : class [OK]
- Applying constraint to wrong type parameter
- Using 'struct' instead of 'class' for reference types
- Omitting constraints when needed
Ready to prove it?
Pass the test and this pattern moves unknown
