But here I am going to discuss about the type of constrain we apply one the custom type we create using generics.
Reference Type
Constrain ensure that type argument is Reference Type. i.e Class, Interface, Delegates, Array etc.
Syntax
Class A<T> where T : classExample
Valid | InValid |
A<MyClass> A<InterfaceME> A<float[]> | A<int> A<float> |
Always come first when multiple constrain applied.
Value Type
Constrain ensure that type argument is Value Type. i.e int, float, struct, enum etc. But not nullable types.
Syntax
Class A<T> where T : struct
Example
Valid | InValid |
A<int> A<float> | A<Myclass> A<InterfaceME> |
Always come first when multiple constrain applied.
Constructor Type
Constrain ensure that type argument must have parameterless constructor to create instance of type argument. i.e any value type; nonstatic, nonabstract with parameterless constructor.
SyntaxClass A<T> where T : new()
Note :
Always come last when multiple constrain applied.
Derived TypeConstrain ensure that type argument must derived or implemented form specified type.
Syntax
Class A<T> where T : MyClass Class A<T> where T : InterfaceMEExample
class A<T> where T : Stream
Valid | InValid |
A<MemoryStream> | A<object> A<string> |
class A<T> where T : IDisposible
Valid | InValid |
A<DataTable> | A<StringBuilder> |
You can specify multiple interface for type argument in this constrain but only one. Because no type can derived from more than once class.
Valid | InValid |
class A<T> where T : Stream,IDisposible,IEnumerable<T> | class A<T> where T : Stream,ArrayList,IEnumerable<T> |
Specified class must not be struct, a sealed class
or not belonging to special type
System.Object System.Enum System.ValueType System.Delegate
Summary
Its good to focus on Constrain type when you are implementing own custom types. This Constrain also applicable to generic methods with type argument.
Great Community here. Keep up the good work people. Backlinks
ReplyDeleteGood article.
ReplyDelete