c# - Generic type vs Extension method -


i need make comparison between 2 techniques : use of generic type , extend type. don't mean general comparison, mean in specific case when need add features class named classa

  1. using generic type

    use generic type ( where t: classa ) , implement generic methods

  2. using extension methods

    use classa adding extension methods

     public static class helper {   public static void methodone(this classa obj, )   {  //   }   } 

i need know :

  • what advantages of each technique in comparison other?
  • why first technique used in repository pattern? example in implementation why don't add extension methods global class entity ?

those 2 entirely different things.

you use generics provide generic functionality. repositories, used "base entity" class or interface containing properties entities implement, id:

public interface ientity {     int id { get; set; } }  public class client : ientity {     public int id { get; set; }     public string name { get; set; }         }  public class repository<t>      t : ientity {     private readonly iqueryable<t> _collection;     public repository(iqueryable<t> collection)     {         _collection = collection;     }      public t findbyid(int id)     {         return _collection.first(e => e.id == id);     } } 

you extension method:

public static t findbyid(this iqueryable<t> collection, int id)     t : ientity {     return collection.first(e => e.id == id); } 

without generics, you'd have implement repository or extension method every type.

why not use extension method in case: use when can't extend base type. repository class can group operations in 1 logical class.

see when use extension methods, ext. methods vs. inheritance?, what cool generics, why use them?.


Comments