top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Please explain detail about Constraints in Generics using C#?

0 votes
370 views
Please explain detail about Constraints in Generics using C#?
posted May 31, 2017 by Jdk

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes
 
Best answer

There are two possible solutions for this (that were bundled out of the box) with C#:

  1. Runtime casting
  2. Restricting the allowable types while declaring the generic type

Runtime casting (a.k.a. yuck!), sometimes, can be a good fit here. In this, the CLR will cast the types at the runtime dynamically thus ensuring the similar functional behavior throughout the application. But, this certainly is not the best way always, especially not when the types being used are overriding the default behavior of the operators (just an example) involved in the operation.

The best fit, for most of the cases would certainly be having some kind of restriction on what types should be allowed to be replaced in the generic type. In .NET, they are called constraints.

Constraints are represented in C# using the where keyword. The following is the syntax:

public bool Compare< T > (T t1, Tt2)
       where T : IComparable 
{
  ...
} 

Some of the ways we can use constraints are as follows:

Specifying the type to be a reference type:

public void MyMethod< T >()
       where T : class
{
  ...
} 

Please note that class is the keyword here and should be used in the same case. Any difference in the case will lead to a compilation error.

Specifying the type to be a value type:

public void MyMethod< T >()
       where T : struct
{
  ...
} 

Please note that struct is the keyword here and should be used in the same case. Any difference in the case will lead to a compilation error.

Specifying a constructor as a constraint:

public void MyMethod< T >()
        where T : new ()
{
  ...
} 

Please note that only a default constructor can be used in the constraints and using any parameterised constructor will be a compilation error.

Specifying a static base class as a constraint:

public void MyMethod< T >()
       where T : BaseClass
{
  ...
}

Specifying a generic base class as a constraint:

public void MyMethod< T, U >()
       where T : U
{
  ...
} 
answer Jun 1, 2017 by Madhavi Kumari
...