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.
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.
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.
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.
new()
constraint allows you to create an instance with new T()
.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.
Only allow types T that are derived from or implement DataContext, and have a public constructor that takes no arguments.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With