Ehsan Ghanbari

Experience, DotNet, Solutions

Generic constraint in C#

When you define a generic class, you can apply the generic type independent on a certain feature. In other words, you help the client code by using constraint to not got the error when instantiating the base Type which is not allowed in constraint condition. By constraining the type parameter, you increase the number of allowable operations and method calls to those supported.

Different kinds of constraints could be like these:

  1. Where T: Class
  2. Where T: struct
  3. Where T: new()
  4. Where T:<ClassName> , new()
  5. Where T:<InterfaceName> , new()


Where constraint :

Where clause:  specifies that constraints on the types that can be used as arguments for a type parameter defined in a generic declaration.


Public Class GenericClass<T,U>  where T: BaseClass1 where U: BaseClass2

Public Class GenericClass<T> : where T: IBaseInterface<T>


New constraints:

New constraints mean that any type argument supplied must have an accessible parameterless constructor.


Public Class MyClass<T> where T:new()


Note that The new() constraint appears last in the where clause. 


Public Class MyClass<T> where T:Icomparable , new()

Public Class MyClass <T> where T: BaseClass, IBaseInterface, IComparable<T> , new()

Public Class MyClass <T,U> where T: class where : IBaseInterface , new()


I have used Generic constraints in a real-world application sample before here. For more information you can see these References:


About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns and I'm spending a lot of my time on architecture subject. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the&nb Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
Peridic pattern
How to use PagedList In MVC
Redis as a cache server
Domain driven design VS model driven architecture
How to query over Icollection<> of a type with linq
What's the DDD-lite?
comments powered by Disqus