c# Why can't open generic types be passed as parameters?
        Posted  
        
            by 
                Rich Oliver
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Rich Oliver
        
        
        
        Published on 2012-03-20T22:46:14Z
        Indexed on 
            2012/03/20
            23:29 UTC
        
        
        Read the original article
        Hit count: 269
        
Why can't open generic types be passed as parameters. I frequently have classes like:
public class Example<T> where T: BaseClass
{
   public int a {get; set;}
   public List<T> mylist {get; set;}
}
Lets say BaseClass is as follows;
public BaseClass
{
    public int num;
}
I then want a method of say:
public int MyArbitarySumMethod(Example example)//This won't compile Example not closed
{
   int sum = 0;
   foreach(BaseClass i in example.myList)//myList being infered as an IEnumerable
       sum += i.num;
   sum = sum * example.a;
   return sum;
}
I then have to write an interface just to pass this one class as a parameter as follows:
public interface IExample
{
public int a {get; set;}
public IEnumerable<BaseClass> myIEnum {get;}
}
The generic class then has to be modified to:
public class Example<T>: IExample where T: BaseClass
{
   public int a {get; set;}
   public List<T> mylist {get; set;}
   public IEnumerable<BaseClass> myIEnum {get {return myList;} }
}
That's a lot of ceremony for what I would have thought the compiler could infer. Even if something can't be changed I find it psychologically very helpful if I know the reasons / justifications for the absence of Syntax short cuts.
© Stack Overflow or respective owner