C# Generics and When We Use Them

Nick Shoup on February 19, 2019

This post was originally published on my blog Fundamentals of Code Generics in C Sharp I wanted to give some demonstrations around th... [Read Full]
markdown guide
 

Please don't dynamic as a part of a generic method. The Add method in your post would throw a runtime exception as soon as you try to call it with a type that doesn't support the + operator - which is basically most types.

The point of Generics is to a allow you to write code that can be reused for multiple types, but to do that properly you have to either write code that doesn't involve the types themselves (like a List<T>, where the generic class only acts as the collection of T) or use generic constraints, that will allow your method/class/property to interact with the T in a truly type safe way.

 

Great intro Nick. You have a nice writing style. And there ar so many places you could go with a follow-up, too... constraints, interfaces, more info on boxing.

 

Thanks Tom! I truly appreciate the feedback. I will be doing additional posts on C# and will either update this post to include constraints as it seems to fit the best here, but was going to do a separate post on boxing/unboxing. Interfaces are also going to be part of separate post.

 

Yep, I was looking for constraints in the article too. I think they go hand in hand with generics.

 

I agree about then going hand in hand. I'm most likely going to update this post to include it.

code of conduct - report abuse