12

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?

Ignazio
  • 10,504
  • 1
  • 14
  • 25
Carra
  • 17,808
  • 7
  • 62
  • 75

6 Answers6

15

it is a constraint for generics

MSDN

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

specializt
  • 1,913
  • 15
  • 26
Pharabus
  • 6,081
  • 1
  • 26
  • 39
9

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.

Jeff Sternal
  • 47,787
  • 8
  • 93
  • 120
5

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.

Joel
  • 5,618
  • 1
  • 20
  • 19
3

This is a generic type constraint. It means that the generic type T must implement a zero parameter constructor.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
3

The Where keyword is basically a constraint on the objects the class can work on/with.

taken from MSDN "The new() Constraint lets the compiler know that any type argument supplied must have an accessible parameterless constructor"

http://msdn.microsoft.com/en-us/library/6b0scde8(VS.80).aspx

Mauro
  • 4,531
  • 3
  • 30
  • 56
1

It means the T has to have a public default constructor.

Codism
  • 5,928
  • 6
  • 28
  • 29