As a followup question to this one
public interface IFeature { }
public class FeatureA : IFeature { }
IFeature a = new FeatureA();
Activate(a);
private static void Activate<TFeature>(TFeature featureDefinition) where TFeature : IFeature
{
}
I undestand, that once the FeatureA
is casted to IFeature
the generic method will always get IFeature
as type parameter.
We have a service with provides us with a list features (List<IFeature>
). If we want to iterate over those features, passing each in the generic method, I guess there is no way to get the concrete type in the generic method other than
- using reflection
- using a dynamic variable to determine the type on runtime (Calling a generic method with the correct derived type)
Since reflection is very costly, I would like to use the dynamic cast. Is there any downside to call the method that way? Somehow I feel dirty when doing that :-)
You can use visitor pattern as follows assuming that you can modify your codebase. Otherwise, use dynamic.
You can obtain the type object for generic/(not generic) type using typeof:
My simple method returns T. And this is a key point. It must be generic to allow developer to specify return type. If method doesn't return generic and only accepts one then there are several reasons to make it generic. To avoid box/unbox operations on method arguments or to tackle with situation when method takes argument of different types which are not inherited from common base class/interface. And it's not your case. So the method in your code haven't to be generic. Just type you argument as IFeature and use is/as/GetType():