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

Default keyword for generic types in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the default keyword do for generic types in C#?
The default keyword returns the default value for a generic type parameter. For reference types, it returns null. For value types, it returns zero or equivalent (like 0 for numbers, false for bool).
Click to reveal answer
beginner
How do you use default to initialize a generic variable T?
You write T variable = default; or T variable = default(T);. Both assign the default value for type T.
Click to reveal answer
intermediate
What is the default value of a generic type parameter T if T is a struct?
If T is a struct (a value type), default(T) returns a struct with all fields set to their default values (like zero for numbers, false for bool).
Click to reveal answer
intermediate
Can default be used with nullable types in generics?
Yes. For nullable types like int?, default returns null, which is the default for nullable types.
Click to reveal answer
beginner
Why is default useful in generic methods or classes?
Because generic types can be any type, default lets you safely get a default value without knowing the exact type. This avoids errors and makes code flexible.
Click to reveal answer
What does default(T) return if T is a reference type?
A0
Bnull
Cfalse
DAn empty object
How can you write the default value for a generic type T in C# 7.1 or later?
A<code>default</code>
B<code>null</code>
C<code>new T()</code>
D<code>default(T)</code>
What is the default value of bool when used as a generic type parameter?
Anull
Btrue
Cfalse
D1
If T is int? (nullable int), what does default(T) return?
A0
Bfalse
CAn exception
Dnull
Why might you prefer default over new T() in generic code?
A<code>default</code> works even if <code>T</code> has no parameterless constructor
B<code>new T()</code> always works
C<code>default</code> creates a new object
D<code>new T()</code> returns null
Explain how the default keyword works with generic types in C#.
Think about what happens when you don't know the exact type.
You got /4 concepts.
    Describe a situation where using default is better than new T() in generic programming.
    Consider constructor requirements.
    You got /4 concepts.