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

C Sharp

1526 readers
31 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
[–] theit8514@lemmy.world 2 points 4 months ago* (last edited 4 months ago) (2 children)

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~~

[–] Cyno@programming.dev 2 points 4 months ago (1 children)

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 1 points 4 months ago* (last edited 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).