Do you use generics? What are they good for? And what are constraints and why to use them?
Experience Level: Mid-level
Tags: .NET C# Performance
- Generics are like class templates, where you can define placeholders within a template and the consumer of the generic class can later define the placeholders himself.
- Generics allow you to write reusable code with high level of flexibility.
- Thanks to generis you don't repeat yourself.
- Generics allow you to design and write classes that are type-safe and can be used with multiple types.
- Generics help you to avoid the performance hit of boxing/unboxing.
When you define Generic class and you don't want the placeholder type T to be anything, you can define constraints that define what the type T can be.
Constraints are defined by using "where T:" keyword.
There are these constraints:
- where T: struct // Type T must be struct (value type)
- where T: class // Type T must be class
- where T: BaseClassName // Type T must be or derive from BaseClassName
- where T: IInterfaceName // Type T must be or must implement the interface IInterfaceName
- where T: new() // Type T must have a public parameterless constructor
- where T: U // Type T must be or derive from the argument supplied for U
Related C# job interview questions
.NET C# Entity Framework LINQ Performance Senior
.NET C# Performance Junior
Could you explain what the following LINQ methods OrderBy, Where and Single do and what will be the output of the code?.NET C# LINQ Junior
Could you explain on the following example what a deferred execution is and what materialization is? What will the output be?.NET C# LINQ Performance Mid-level
.NET C# Mid-level