Is it possible for a non-generic class contain a generic list in .NET (C# or VB.NET)?
.net, c#, c#-2.0, generics, vb.net
Solution
This is a fairly common problem. What you need to do is either declare a non-generic base class that your generic class inherits from or a non-generic interface that your generic class implements. You can then make your collection of that type.
For example,
public abstract class CollectionColumnBase
{
private string _name;
private string _displayName;
public string Name {
get { return _name; }
set { _name = value; }
}
public string DisplayName {
get { return _displayName; }
set { _displayName = value; }
}
public abstract object GetItemAt(int index);
}
public class CollectionColumn<T> : CollectionColumnBase
{
private List<T> data = new List<T>();
public overrides object GetItemAt(int index)
{
return data[index];
}
public List<T> Items
{
get { return data; }
set { data = value; }
}
}
public class ColumnCollection
{
public int Id { get; set; }
public string ContainerName { get; set; }
private List<CollectionColumnBase> _columns;
public List<CollectionColumnBase> Columns {
get { return _columns; }
set { _columns = value; }
}
}
Problem
I'm hoping someone can assist me with understanding if/how something like this is possible. In this scenario, imagine you are trying to model a grid like a spreadsheet or in a DB, but where the data in each column can only be of one data type. Example: Column 1 can only contain integers. I created a generic class to model the column structure that looks like this: ``` public class CollectionColumn<T> { private string _name; private string _displayName; private List<T> _dataItems = new List<T>(); public string Name { get { return _name; } set { _name = value; } } public string DisplayName { get { return _displayName; } set { _displayName = value; } } public List<T> Items { get { return _dataItems; } set { _dataItems = value; } } } ``` Now what I want to do is have a container for the various columns (there could be CollectionColumn, CollectionColumn, etc.) with it's own properties, but I'm not sure how to do that where I can still access the columns and the data within them when I don't know their types. This is a .NET 2.0 project so something like dynamic would not work, maybe a list of object? I am also not sure if there is a way to do this with interfaces. ``` public class ColumnCollection { public int Id { get; set; } public string ContainerName { get; set; } private List<CollectionColumn<T>> _columns; public List<CollectionColumn<T>> Columns { get { return _columns; } set { _columns = value; } } } ``` What I want to be able to do is add various CollectionColumn's to the Columns collection of a ColumnCollection so I can have columns containing various types of data. Any help would be very much appreciated.