Consider the following code:
public dynamic DataGrid { get; private set; }
public DataGridForm<TData, TGrid> GridConfig<TData, TGrid>() where TData : class
{
return DataGrid = new DataGridForm<TData, TGrid>();
}
I'm trying to keep an instance of a generic class in a property
for later usage, but as you know:
Properties, events, constructors etc can't be generic - only methods and types can be generic. Most of the time that's not a problem, but I agree that sometimes it's a pain (Jon Skeet)
I want to know is this a good way to round this situation?
As the answer in the comment indicated, you can do this with a base class or an interface:
class DataGridForm {}
class DataGridForm<TData, TGrid> : DataGridForm {}
class GridConfigurator
{
public DataGridForm DataGrid { get; private set; }
public DataGridForm<TData, TGrid> GridConfig<TData, TGrid>() where TData : class
{
return DataGrid = new DataGridForm<TData, TGrid>();
}
}
A ton of types and interfaces in C# were expanded this way when generics were added. However, I would probably re-evaluate your design so that perhaps whatever called GridConfig() was caching the DataGridForm since it knows the types. As an example, I do a very similar thing in my code:
class Vector<T> { ... }
static class Vector
{
public static Vector<T> Create<T>(T value)
{
return new Vector<T>(value);
}
}
class OtherClass
{
public static Vector<int> MyVector = Vector.Create(1);
}
Your specific use case may not support this style though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With