Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "where" mean in a C# class declaration?

Tags:

c#

.net

generics

I tried to google this, but all I could find was documents on ordinary class declarations.

public class DataContextWrapper<T> : IDataContextWrapper where T : DataContext, new()
{

}

I see that the class implements IDataContextWrapper, inherits from DataContext and varies with type T depending on how it is instantiated.

I don't know what "where T" or the ", new()" might mean.

like image 612
MatthewMartin Avatar asked Jan 03 '11 15:01

MatthewMartin


People also ask

What does where mean in C#?

The where keyword is used to constrain your generic type variable, in your case it means that the type T must be a DataContext and must contain a public default constructor.

What does where T class mean?

it means that the type used as T when the generic method is used must be a class - i.e. it cannot be a struct or built in number like int or double // Valid: var myStringList = DoThis<string>(); // Invalid - compile error var myIntList = DoThis<int>(); Copy link CC BY-SA 2.5.


4 Answers

It's a generic constraint and restricts what types can be passed into the generic parameter.

In your case it requires that T is indentical to or derived from DataContext and has a default(argumentless) constructor(the new() constraint).

You need generic constraints to actually do something non trivial with a generic type.

  • The new() constraint allows you to create an instance with new T().
  • The DataContext constraint allows you to call the methods of DataContext on an instance of T

MSDN wrote:

where T : <base class name> The type argument must be or derive from the specified base class.

where T : new() The type argument must have a public parameterless constructor. When used together with other constraints, the new() constraint must be specified last.

like image 118
CodesInChaos Avatar answered Sep 24 '22 08:09

CodesInChaos


Only allow types T that are derived from or implement DataContext, and have a public constructor that takes no arguments.

like image 40
Timbo Avatar answered Sep 25 '22 08:09

Timbo


It's a generic type constraint and specifies constraint on the generic types (for example, only classes, or must implement a specific interface).

In this case, T must be a class that is either DataContext or inherits from it and must have a parameterless public constructor (the new() constraint).

like image 33
Oded Avatar answered Sep 24 '22 08:09

Oded


It's a generic type restriction. In this case, T must inherit from DataContext and be a type with a constructor that takes no arguments.

like image 28
Matt Kellogg Avatar answered Sep 25 '22 08:09

Matt Kellogg