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)

You are viewing a single thread.
View all comments
1 point

You can actually use the dynamic type here for late binding of overloads. You will get a runtime error for unknown types though.

You essentially define the function overloaded for each type. Then call the function with a dynamic and the runtime will figure out what method to call

permalink
report
reply

C Sharp

!csharp@programming.dev

Create post

A community about the C# programming language

Getting started

Useful resources

IDEs and code editors

Tools

Rules

  • Rule 1: Follow Lemmy rules
  • Rule 2: Be excellent to each other, no hostility towards users for any reason
  • Rule 3: No spam of tools/companies/advertisements

Related communities

Community stats

  • 22

    Monthly active users

  • 62

    Posts

  • 32

    Comments