Saturday, January 15, 2011
a good blog about generic and constrain it with "where"
James M. Hare's blog about constraining generics with "where" clause
The blog is thorough. Store it for future reference.
To summarize some key syntaxs as below:
- constrains to an interface or a base class
public class MyClass<T> where T : IMyInterface<T>
- constrains to reference type
where T : class
- Constrain to value type
where T : struct
- Constrain to required consturctor
Where T: class, new()
"Basically, the where clause allows you to specify additional constraints on what the actual type used to fill the generic type placeholder must support." In another word, "if the type meets the given constraint, you can perform the activities that pertain to that constraint with the generic placeholders."
This empowers you to write less code across types. Less is more.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment