Generics is a powerful feature that allows us to write type safe and reusable code. Generic class enables us to write code without worrying about actual type and defers the type specification to the consumer class or client. This allows us to keep the internal algorithms same for different types. In essence, Generic allows us to parameterize the type used inside a class.
- //Generic Class
- public class Repository<T> : IRepository<T> where T:class
- {
- protected readonly DbContext _context;
- public IEnumerable<T> GetALL() { return _context.Set<T>().ToList<T>(); }
- }
- //Generic Interface
- public interface IRepository<T> where T : class
- {
- IEnumerable<T> GetALL();
- }
- //Generic Method
- public static Nullable<T> GetQueryString<T>(string key) where T : IConvertible
- {
- T result = default(T);
- if (String.IsNullOrEmpty(HttpContext.Request.Query[key]) == false)
- {
- string value = HttpContext.Request.Query[key].ToString();
- try
- {
- result = (T)Convert.ChangeType(value, typeof(T));
- }
- catch
- {
- //Could not convert. Pass back default value...
- result = default(T);
- }
- }
- return result;
- }
- // Generic Delegate
- public delegate void notify<T>(T target) where T : class;
Generic Constraints
Constraints help us to define the allowed types and also restricts the consumer from improper use of the class.
T should be a value type : class Repository<T> where T:struct
T should be a reference type : class Repository<T> where T:class
T should have a parameter less constructor: class Repository<T> where T:new()
T should inherit from a type : class Repository<T> where T:Entity
T should implement a interface : class Repository<T> where T:IEntity
Multiple Constrains
When we specify multiple constarints, there are some orders that need to be followed. For example, base class constraint should come first and the new() constraint should come last etc.
class Requester<T> where T:Customer,IDiscouts
class Requester<T> where T:Customer,IDiscouts,new()
Different Generics type declaration
unbound type
An unbound Generic type cannot exist as a instantiated object, but only as a system.type reference. In addition to that, it will not have any type arguments specified.
typeof(List <>)
Constructed type
An Constructed Generic type has at least one type argument specified.
class sample <T,T>
class sample <T,string>
class sample <int,string>
Open Generic type
Any type which has a type parameter.
class sample <T,T>
class sample <T,string>
Closed type
class sample <int,string>
Covariance in Generics

Join the conversation! Your thoughts help the community grow.