3 ms·
Generics in C# is crazy good, both in writing and using them, all while the compiler checks the correctness especially if combined with constraints. I've tried
by BatteryMountain 5y ago
Generics in C# is crazy good, both in writing and using them, all while the compiler checks the correctness especially if combined with constraints. I've tried "generics" in other languages but they all fall short compared with C#'s way. Between reflection, generics, polymorphism, dependency injection, you have a winning combo of code reuse. Can turn thousands of normal lines of code into a few hundred. I've surprised myself again again on how useful it can be, all without getting lost in the abstractness of it. The people at the dotnet team who carefully thought it through and implemented it deserves a ton of recognition for this.
- ithkuil 5y agoCan you summarize the aspects of C# generics that are different/better than other similar languages?
- torginus 5y agoEh, It can be good or bad. While generics (in C#) can make your code easier to use correctly, by making sure that everything is of the right type, and can give you a nice perf boost when using generic specialization with structs, they also have a tendency of infecting every bit of code they affect with more generics. For example if a function is generic over T, where T is parameter X constrained to be `ISomething`, all the function that it calls with X should use constrained generics as well, this can easily lead to the explosion of generic functions in your codebase. Many times, instead of making a function generic over T it's easier to make parameter X just be interface `ISomething` and be done with it.
- BatteryMountain 5y agoVery good point. I typically use both approaches, sometimes using an interface as a method parameter just "feels" more natural, but other times a generic + type constraint is better. I usually draw the line when the infection you mention becomes too much, aka when 3 or 4 layers are now forced to use a generic cause 1 layer needed it. So yes, very valid point. The key is to find balance so that the code is still maintainable in 6 months from now, still readable + fast, while trying to reduce duplication where it makes sense.