Search code examples
c#genericsc#-4.0enumstype-parameter

Create type parameter based on another value


Don't know if this has been asked before, so point me to another question if it has.

I've got a method like this:

private void SomeMethod<TLocation>(int x, int y) where TLocation : DataLocation
{
   //
}

In the method i wish to call it with, i have an enum, and i want to call the method with the type parameter.

public enum LocationType
{
   Country,
   State,
   County,
   City,
   Neighborhood,
   Street
}

Types of DataLocation:

DataCountry
DataState
DataCounty
DataCity
DataNeighborhood
DataStreet

Knowing that the type parameter is "Data" + enum name, is there any way i can dynamically call my method?

Or should i stick with:

switch (locationType)
{
   case LocationType.Country: 
      SomeMethod<DataCountry>(1, 2);
      break;
   case LocationType.State:
      SomeMethod<DataState>(2, 4);
      break;
   // etc
}

EDIT:

Looks like reflection is the only way. I'll be sticking with the switch.


Solution

  • Here is the possible solution:

    var dispatches = new Dictionary<LocationType, Action<int, int>>();
    dispatches.Add(LocationType.Country, SomeMethod<DataCountry>);
    dispatches.Add(LocationType.State, SomeMethod<DataState>);
    //... and etc.
    
    dispatches[LocationType.Country](1, 2); // the same as SomeMethod<DataCountry>(1,2)