Do you use generics? What are they good for? And what are constraints and why to use them?

Experience Level: Medior
Tags: .NETC#Performance

Answer

Explanation

  • 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

Comments

No Comments Yet.
Be the first to tell us what you think.
.NET challenge
.NET challenge

Are you learning C# ? Try our test we designed to help you progress faster.

Test yourself
.NET/C# Phone Screening 1
.NET/C# Phone Screening 1

Are you learning C# ? Try our test we designed to help you progress faster.

Test yourself