0

I am fetching the SomeThingType from the db, and then want to make a call to the SomeThing<T>(T value). I am getting the type from the db at runtime.

I'm stuck, how can I do this?

ProductType productType = GetProductType(userId);
SomeThingType someThingType = GetSomeThingTypeFromDb(userId);

switch(productType)
{
    case ProductType.ONE:
        // stuck here                           
            IThing<int> a = new SomeThing<int>(..);
        IThing<string> a = new SomeThing<string>(..);
        IThing<DateTime> a = new SomeThing<DateTime>(..);
        break;
}

I'm stuck on how I can use the correct generic type based on a enumeration value that I retrieve at runtime from the database.

The db value maps to an enumeration that I want to use to figure out which generic type I should use, either a string, int or DateTime.

Is this something that I can solve in c#? Or is this only possible in a dynamic language?

codecompleting
  • 9,251
  • 13
  • 61
  • 102

1 Answers1

3

You cannot do this if you need to have the closed generic type (like IThing<int>) in your case blocks.

If you do not need it, just create a non-generic interface IThing from which IThing<T> is derived. Then have a method that creates the appropriate instance depending on the enum value.

void Foo()
{
    ProductType productType = GetProductType(userId);
    SomeThingType someThingType = GetSomeThingTypeFromDb(userId);

    switch(productType)
    {
        case ProductType.ONE:
            IThing a = CreateThing(someThingType, ...);
            break;

        ...
    }

    ...
}

IThing CreateThing(SomeThingType someThingType , ...)
{
    switch(someThingType )
    {
        case SomeThingType.X:
            return new SomeThing<int>(...);

        case SomeThingType.Y:
            return new SomeThing<string>(...);

        case SomeThingType.Z:
            return new SomeThing<DateTime>(...);

        default:
            throw new ArgumentException(...);
    }
}
Florian Greinacher
  • 14,478
  • 1
  • 35
  • 53
  • thanks that will work, I have allot of cases for the productType, that means for each one I will have to write a CreateThing helper....I wish there was an easier way! – codecompleting Oct 25 '11 at 19:18