Overview
Generics in C# allow you to define a class, method, or interface with a placeholder for the type it operates on. This approach promotes code reusability, type safety, and performance. Using generics, developers can create flexible and maintainable codebases that work with any data type, reducing the need for type casting and the risk of runtime errors.
Key Concepts
- Type Safety: Generics provide compile-time type checking, minimizing runtime errors.
- Code Reusability: Generics enable developers to write code that works with any data type.
- Performance: Using generics can lead to better performance by eliminating the need for boxing and unboxing.
Common Interview Questions
Basic Level
- What are generics in C#?
- Can you write a simple generic method in C#?
Intermediate Level
- How do generics improve type safety and performance in C#?
Advanced Level
- Can you discuss how constraints on type parameters in generics enhance their usefulness?
Detailed Answers
1. What are generics in C#?
Answer: Generics are a feature in C# that allows code to be defined with placeholders for the type of data it operates on. This flexibility enables functions, classes, interfaces, and delegates to be reused with different data types while maintaining strong type safety.
Key Points:
- Generics increase code reusability.
- They ensure compile-time type safety.
- They eliminate the need for boxing and unboxing.
Example:
// Defining a generic class
public class GenericList<T>
{
public void Add(T input) { }
}
// Using the generic class
var list = new GenericList<int>();
list.Add(1);
2. Can you write a simple generic method in C#?
Answer: Yes, a generic method can be defined within a non-generic class. This method will be capable of working with any data type specified at the time of invocation.
Key Points:
- Generic methods provide flexibility.
- They enable code reuse for different data types.
- Type safety is ensured at compile time.
Example:
public class Utility
{
// Generic method to swap two elements
public static void Swap<T>(ref T lhs, ref T rhs)
{
T temp;
temp = lhs;
lhs = rhs;
rhs = temp;
}
}
// Example usage
int a = 1, b = 2;
Utility.Swap<int>(ref a, ref b);
3. How do generics improve type safety and performance in C#?
Answer: Generics improve type safety by ensuring that only the correct type of data is used with them, detected at compile-time rather than runtime. For performance, generics eliminate the need for boxing and unboxing when working with value types, as operations on generic collections do not incur the overhead of converting to and from object
.
Key Points:
- Compile-time type checking reduces runtime errors.
- Performance is enhanced by avoiding boxing and unboxing.
- Strongly typed collections eliminate the need for casts.
Example:
// Using a generic list eliminates the need for boxing/unboxing
List<int> numbers = new List<int>();
numbers.Add(10); // Directly stores the value type without boxing
4. Can you discuss how constraints on type parameters in generics enhance their usefulness?
Answer: Constraints on type parameters allow developers to specify the requirements for the types that can be used with generic types or methods. This capability ensures that the generic types or methods can safely assume certain properties or behaviors of the types they work with, leading to more robust and reliable code.
Key Points:
- Constraints enforce type safety beyond compile-time checks.
- They enable the use of specific methods or properties on the constrained types.
- Constraints can limit generic types to reference types, value types, constructors, and interfaces.
Example:
public class GenericRepository<T> where T : class, new()
{
public T CreateInstance()
{
return new T(); // Ensures T has a parameterless constructor
}
}
// This ensures that T is a class that can be instantiated with a parameterless constructor.
This guide covers the essentials of generics in C# and delves into advanced topics like type constraints, illustrating their importance in creating efficient, type-safe, and reusable code.