Is it possible for a non-generic class to contain a generic list in .NET (C # or VB.NET)?

I hope someone can help me with understanding if / how it is possible.

In this case, imagine that you are trying to model a grid, for example, a spreadsheet or in a database, but where the data in each column can be only one data type.

Example: Column 1 can contain only integers.

I created a general class for modeling the column structure, which 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 various columns (maybe CollectionColumn, CollectionColumn, etc.) with its own properties, but I'm not sure how to do this when I can access the columns and data in them when I don't know their types.

This is a .NET 2.0 project, so something like dynamic doesn't work, maybe a list of objects? I'm also not sure if there is a way to do this using 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 do is add various CollectionColumn to the Columns ColumnCollection so that I can have columns containing different data types.

Any help would be greatly appreciated.

+7
source share
1 answer

This is a fairly common problem. What you need to do is either declare a base class that does not have a generic class inherited by your generic class, or not a generic interface that is implemented by your generic class. Then you can make your collection of this 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; } } } 
+10
source

All Articles