Search code examples
c#.netgenericsgeneric-collections

Casting a generic type in c#


I have a structure like below. I have some trouble returning a generic collection. What am I missing ?

class Program
{
    static void Main()
    {
          BusinessCollection businessCollection = new BusinessCollection();

          //Why this is not working because businesscollection is a GenericCollection<BusinessEntity>
          businessCollection = new GenericCollection<BusinessEntity>();

          //or neither this
         businessCollection = (BusinessCollection)new GenericCollection<BusinessEntity>();
    }
}



public class BusinessEntity
{
   public string Foo { get; set;}
}

public class BusinessCollection : GenericCollection<BusinessEntity>
{
     //some implementation here
}

public class GenericCollection<T> : ICollection<T>
{
    //some implementation here
}

Solution

  • You can't do what you want to do. The other way around will work.

    All BusinessCollection are indeed GenericCollection<BusinessEntity> but you can't say for sure that all GenericCollection<BusinessEntity> are BusinessCollection's

    So the following will work.

    class Program
    {
        static void Main()
        {
              GenericCollection<BusinessEntity> businessCollection = new BusinessCollection();
              //this will work
              BusinessCollection tempCollection = (BusinessCollection)businessCollection ;
        }
    }
    
    
    
    public class BusinessEntity
    {
       public string Foo { get; set;}
    }
    
    public class BusinessCollection : GenericCollection<BusinessEntity>
    {
         //some implementation here
    }
    
    public class GenericCollection<T> : ICollection<T>
    {
        //some implementation here
    }