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 word you help the client code by using constraint to not got error when instantiate 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.

  1. Public Class GenericClass<T,U>  where T: BaseClass1 where U: BaseClass2
  2. {
  3. }
  4.  
  5. Public Class GenericClass<T> : where T: IBaseInterface<T>
  6. {
  7. }

 

New constrains:

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

  1. Public Class MyClass<T> where T:new()
  2. {
  3. }

 

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

  1. Public Class MyClass<T> where T:Icomparable , new()
  2. {
  3. }

 

  1. Public Class MyClass <T> where T: BaseClass, IBaseInterface, IComparable<T> , new()
  2. {
  3. }

 

  1. Public Class MyClass <T,U> where T: class where : IBaseInterface , new()
  2. {
  3. }

 

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

  1. http://msdn.microsoft.com/en-us/library/d5x73970.aspx
  2. http://www.dotnetperls.com/generic

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. I spend a lot of time on software architecture. Since 2008, I've been as a developer for different companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the past years, Read More

Post Tags
Pending Blog Posts
using Elmah in asp.net MVC4
Using FluentSecurity in MVC
Strategic design
Factory Pattern
time out pattern in ajax
Redis as a cache server
How to use PagedList In asp.net MVC
Multiple submit buttons in asp.net MVC
Domain driven design VS model driven architecture
What's the DDD-lite?
comments powered by Disqus