this post was submitted on 11 Jul 2024
5 points (100.0% liked)

C Sharp

1501 readers
1 users here now

A community about the C# programming language

Getting started

Useful resources

IDEs and code editors

Tools

Rules

Related communities

founded 1 year ago
MODERATORS
 

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(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 ?

Can I have a method on the field object that will somehow give me a 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 comment's thread
view the rest of the comments
[–] [email protected] 1 points 2 months ago

if i have to manually handle every case in a switch (or if else) statement and I was wondering how could I write, for example, a method that would do the conversion

You could still do it that way with a switch. Only the case part needs to be constant...

` switch (field.GetType().ToString()) {

case "Int": Method((int)x)...

case "NullInt": Method((int?)x)...

case "Long": Method((long)x)... `

Been a while since I last did this though - you may need to do string caseType=field.GetType().ToString() first, then do switch(caseType). I think from memory you can do it the other way though.

P.S. I clicked on "code" (which just starts/ends with an apostrophe), but it doesn't want to display as code - I don't know why