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@lemmy.world
    link
    fedilink
    arrow-up
    2
    ·
    edit-2
    5 months ago

    If you don’t want to go the pattern matching route you can also use reflection with MakeGenericMethod to specify the generic type and then invoke it.

    Untested example:

    var type = field.GetType();
    var methodInfo = typeof(GenericClass).GetMethod("GenericMethod").MakeGenericMethod(type);
    methodInfo.Invoke(null, field);
    

    Edit: wrong documentation link https://learn.microsoft.com/en-us/dotnet/api/system.reflection.methodinfo.makegenericmethod?view=net-8.0 ~~https://learn.microsoft.com/en-us/dotnet/api/system.reflection.emit.methodbuilder.makegenericmethod?view=net-8.0~~

    • CynoOP
      link
      fedilink
      arrow-up
      2
      ·
      5 months ago

      I have this instinct drilled into me for years that anything using reflection is bad, both in terms of performance or code clarity/ease of debugging. Your answer is correct though, I could make a generic method using reflection… now I’m just not sure if it’s better to just manually hardcode the cases for all types anyway

      • theit8514@lemmy.world
        link
        fedilink
        arrow-up
        1
        ·
        edit-2
        4 months 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).