Passing generics to non generic classes
-
I have a class that uses generics to have a typesafe DataSource property. I want to pass an instance of this class to a form and have it display the datasource. The code looks something like this:
public class DataSource<ItemType> where ItemType : StatefulObjectBase
{
public ItemType DataSource
{
....
}public void Show() { DisplayForm f = new DisplayForm(this); }
}
The question is, how do I code the parameter on the forms constructor. Using DataSource<StatefulObjectBase> doesnt work, even though the compiler should know that whatever is in the object is convertible to that type. Even using object didnt work. All I want to do from the form is access some methods from my generic object. I dont care what type they are. Any help would be much appreciated. EDIT: oops, fixing generics.. damn less than and great thans -- Dave
-
I have a class that uses generics to have a typesafe DataSource property. I want to pass an instance of this class to a form and have it display the datasource. The code looks something like this:
public class DataSource<ItemType> where ItemType : StatefulObjectBase
{
public ItemType DataSource
{
....
}public void Show() { DisplayForm f = new DisplayForm(this); }
}
The question is, how do I code the parameter on the forms constructor. Using DataSource<StatefulObjectBase> doesnt work, even though the compiler should know that whatever is in the object is convertible to that type. Even using object didnt work. All I want to do from the form is access some methods from my generic object. I dont care what type they are. Any help would be much appreciated. EDIT: oops, fixing generics.. damn less than and great thans -- Dave
There are couple problems with this. 1. You cannot have public ItemType DataSource property as DataSource is name of the class 2. C# does supports generic methods, but not generic constructors. You can write your code like:
public interface StatefulObjectBase { } public class DataSource where ItemType : StatefulObjectBase { public ItemType TheDataSource { get { return default(ItemType); } } public void Show() { DisplayForm f = new DisplayForm(); f.Show(this); } } public class DisplayForm { public DisplayForm() { } public void Show(DataSource source) where ItemType : StatefulObjectBase { } }