Let’s say I have a method that I want to make generic, and so far it had a big switch case of types.

For an simplified example,

switch (field.GetType()) {
case Type.Int: Method((int)x)...
case Type.NullInt: Method((int?)x)...
case Type.Long: Method((long)x)...

I’d like to be able to just call my GenericMethod<T>(field) instead and I’m wondering if this is possible and how would I go around doing it.

GenericMethod(field)

public void GenericMethod<T>(T field)

Can I use reflection to get a type and the pass it into the generic method somehow, is it possible to transform Type into <T>?

Can I have a method on the field object that will somehow give me a <T> type for use in my generic method?

Sorry for a confusing question, I’m not really sure how to phrase it correctly, but basically I want to get rid of switch cases and lots of manual coding when all I need is just the type (but that type can’t be passed as generic from parent class)

  • @theit8514
    link
    1
    edit-2
    1 month ago

    Yes, I agree that this is a bit of an anti-pattern, as you lose quite a few benefits from the Generics compile-time safety and instead open yourself to runtime exceptions. Not sure what your use case is, but if you want to maintain type safety it might be better to have multiple overloads for each type you want to process rather than a Generic. Typically you use Generics when the actual type doesn’t matter to the method being called (e.g. LINQ uses Generics for IEnumerable<T>.Where because T can be anything and it just calls a Func<T, bool> on each element).