Friday, July 17, 2015

C# Generic study

Generic Constraints

Generic Constraints is used when T in the class needs to have specific characteristics/methods that object type doesn't have (object type has only "toString" and "hasHashCode" methods).
  • "where" keyword can be used to constrain the generic type, for example: 
    • public class SqlRepository<T> : IRepository<T> where T : class
  • we can create a new interface with such method and use "where" keyword to constrain T. for example:
    • public interface IEntity {bool IsValid()} so that "where T : IEntity" will allow "T.IsValid()".
    • Note. usually we do not need to define own interface, check in advance if .net framework already has such!
  • default(T) will assign default value to T. if T is class -> null; if T is struct -> 0
  • where T : new() -> T has a default constructor so that T can be instantiated in code, for example:
    • public T CreateNewT() {T t = new T(); return t;}
  • constraints is preferable to be implemented in concrete class instead of in interface
  • Covariant V.S. Contravariant
  •  public interface IReadOnlyRepository<out T> : IDisposable  
         T FindById(int id);  
         IQueryable<T> FindAll();  
       public interface IWriteOnlyRepository<in T> : IDisposable  
         void Add(T newEntity);  
         void Delete(T entity);  
         int Commit();  
       public interface IRepository<T> : IReadOnlyRepository<T>, IWriteOnlyRepository<T>  
     using (IRepository<Employee> employeeRepository   
             = new SqlRepository<Employee>(new EmployeeDb()))  
  • Reflection in C# (for Generic part)  // ToDo

No comments:

Post a Comment