Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using dynamic type instead of none-possible generic properties

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?

like image 365
saber Avatar asked Jul 24 '13 13:07

saber


1 Answers

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.

like image 129
lukegravitt Avatar answered Oct 13 '22 10:10

lukegravitt