this post was submitted on 11 Jul 2024
5 points (100.0% liked)
C Sharp
1526 readers
2 users here now
A community about the C# programming language
Getting started
Useful resources
- C# documentation
- C# Language Reference
- C# Programming Guide
- C# Coding Conventions
- .NET Framework Reference Source Code
IDEs and code editors
- Visual Studio (Windows/Mac)
- Rider (Windows/Mac/Linux)
- Visual Studio Code (Windows/Mac/Linux)
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
founded 1 year ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
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
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 aFunc<T, bool>
on each element).