Nitha Paul
Nitha Paul

Reputation: 1401

Generic method with class & new() keyword

 public class ViewModelBaseEx<T> : ViewModelBase where T : class, new()
 {
      //...........
 }

I found a class like this in a sample. In this class what is the meaning of portion "where T : class, new()". what is the use of class, new() in this method definition.

Upvotes: 3

Views: 1026

Answers (6)

xanatos
xanatos

Reputation: 111850

It means that T must be a reference type (normally a class, interface, delegate or array) (but not a struct) and that it must have a public parameterless constructor T() (so this will rule out all the previous with exception of class).

Upvotes: 10

Ehsan
Ehsan

Reputation: 32681

Basically class, new() are adding constraints.

class means that it should be of type class (structs etc are not allowed)

new() represents that it must have a public constructor which takes no parameters.

Upvotes: 1

Tamas Ionut
Tamas Ionut

Reputation: 4410

"class" basically means that "T" is a class type (could be a struct as well => primitive type). The "new()" syntax means that "T" is a class that has an empty constructor so in your class you could do something like:

var obj = new T();

Upvotes: -1

Simon Whitehead
Simon Whitehead

Reputation: 65069

It is a generic type constraint.

It specifies that whatever T is, it must be a reference type (a class) and it must have a public default parameterless constructor (new()).

This allows people to do this:

var x = new T();

Without the new() constraint, that isn't possible.

Upvotes: 7

Rex
Rex

Reputation: 2140

class here is to constraint T to be of Class only, i.e, cannot be structure and other value types.

new() here is to constraint T has to have an empty constructor.

for more information on type constraint, look at the MSDN: http://msdn.microsoft.com/en-us/library/d5x73970.aspx

Upvotes: 0

Matthew Watson
Matthew Watson

Reputation: 109567

It means that T must be a reference (class) type and that it must also have a public default constructor.

See here for more information: http://msdn.microsoft.com/en-us/library/d5x73970.aspx

Upvotes: 0

Related Questions