Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# where keyword [duplicate]

Tags:

c#

In the following piece of code (C# 2.0):

public abstract class ObjectMapperBase< T > where T : new()
{
    internal abstract bool UpdateObject( T plainObjectOrginal,
                                         T plainObjectNew,
                                         WebMethod fwm,
                                         IDbTransaction transaction );
}

Inheritor example:

public abstract class OracleObjectMapperBase< T > : ObjectMapperBase< T > where T : new()
{
    internal override bool UpdateObject( T plainObjectOrginal,
                                         T plainObjectNew,
                                         WebMethod fwm,
                                         IDbTransaction transaction )
    {
        // Fancy Reflection code.
    }
}

What does the where keyword do?

like image 722
Carra Avatar asked May 05 '10 14:05

Carra


3 Answers

it is a constraint for generics

MSDN

so the new() constraint says it must have a public parameterless constructor

like image 147
Pharabus Avatar answered Nov 07 '22 13:11

Pharabus


It specifies a constraint on the generic type parameter T.

The new() constraint specifies that T must have a public default constructor.

You can also stipulate that the type must be a class (or conversely, a struct), that it must implement a given interface, or that it must derive from a particular class.

like image 9
Jeff Sternal Avatar answered Nov 07 '22 12:11

Jeff Sternal


The where clause is used to specify constraints on the types that can be used as arguments for a type parameter defined in a generic declaration. For example, you can declare a generic class, MyGenericClass, such that the type parameter T implements the IComparable interface:

public class MyGenericClass<T> where T:IComparable { }

In this particular case it says that T must implement a default constructor.

like image 5
Joel Avatar answered Nov 07 '22 12:11

Joel