Understanding Generics in C#

Abnoan Muniz
4 min readJan 28, 2023

--

C# | Generics | Understanding Generics | object-oriented | object-oriented programming

If you’re a C# developer, you’ve likely heard of collections and generics. But do you truly understand the power and flexibility they offer? In this post, we’ll dive deep into the world of collections and generics in C#, and I’ll do my best to make it as entertaining as possible. But first, let’s start with the basics.

A collection is simply a group of objects. In C#, the System.Collections namespace provides several classes for working with collections, such as ArrayList, Stack, and Queue. However, these classes have a major drawback: they are not type-safe. This means that you can add any object to a collection, and when you retrieve it, you have to cast it back to its original type. This can lead to runtime errors if you're not careful.

Enter generics. Generics allow you to create type-safe collections. The System.Collections.Generic namespace provides several generic collection classes, such as List<T>, Stack<T>, and Queue<T>. The <T> denotes a type parameter, which can be any type. This means that when you create a List<T>, you specify the type of objects it will contain, such as List<int> or List<string>. This eliminates the need for casting and provides better performance.

But generics aren’t just for collections. They can be used for any type, including classes, interfaces, and methods. Let’s look at an example.

public class MyClass<T>
{
private T _value;

public MyClass(T value)
{
_value = value;
}

public T GetValue()
{
return _value;
}
}

In this example, we have a class called MyClass<T> that has a private field of type T and a constructor that takes a value of type T. The GetValue method returns the value of the private field. Because T is a type parameter, it can be any type. This means we can create an instance of MyClass<int>, MyClass<string>, or MyClass<MyOtherClass>.

It’s not just the classes that are generic. The methods can also be generic. Take a look at this example:

public T Add<T>(T a, T b)
{
return (dynamic)a + (dynamic)b;
}

In this example, the Add method is generic and it takes two parameters of the same type T, and will return the sum of the two values passed as parameters, but it uses the dynamickeyword to be able to handle any type.

But that’s not all. Generics also allow for constraints. Constraints specify the requirements that the type parameter must meet. For example, you might want to create a method that only works with classes that implement a certain interface. You can use the where keyword to specify a constraint, like this:

public void DoSomething<T>(T value) where T : IMyInterface
{
//...
}

In this example, the DoSomething method has a type parameter T that is constrained to types that implement the IMyInterface interface. This means that you can only pass in objects that implement IMyInterface to the DoSomething method. This powerful feature allows you to ensure that certain functionality is available for the type passed in as a parameter.

Lastly, collections and generics are crucial elements for C# developers. They enable the creation of type-safe collections and classes, interfaces, and methods that are adaptable to any type. Additionally, generics can set constraints, guaranteeing that specific functionality is accessible for the type passed as a parameter. Strong comprehension of collections and generics will result in more stable and maintainable code. So, it’s time to put your knowledge into practice and start building fantastic generic collections!

Get ready to laugh, learn, and maybe even cry (from frustration) as we dive deep into the wild world of object-oriented programming with C#. Buckle up folks, cause this series is going to be a wild ride of understanding fundamental concepts. So sit back, relax, and let the good times roll (and the code flow).

Classes and Objects, Inheritance, Abstraction, Encapsulation, Polymorphism, Interfaces, Access Modifiers and Properties, Exception Handling, Generics, Constructors, Delegates and Events.

--

--

Abnoan Muniz

Senior .NET Developer, Passionate about problem-solving. Support me: https://ko-fi.com/abnoanmuniz, Get in touch: linktr.ee/AbnoanM