DEV Community

Cover image for Quick Tour Of Generics In C#
Dane Balia
Dane Balia

Posted on

7 5

Quick Tour Of Generics In C#

Generics have been around since C# 2.0 and has become a tool we leverage so naturally now in C# we almost don't even think about it. So let's change that...

Definitions

Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code.

Essentially generics allow you parameterize types and methods. Just as normal methods have parameters to tell them what values to use, generic types and methods have type parameters to tell them what types to use.

Clarification

Type parameters are placeholders for a type.

There are constructed types and generic types.
A constructed type is when the type arguments are specified. For example,

Dictionary<int, string>()

A generic type is when the type arguments are not specified. For example,

Dictionary<TKey, TValue>()

As per the code snippet below, writing a method to swap two Integer values is pretty rudimentary. But what if later we needed to do the very same but with Strings. This would result in two methods, or perhaps overloads.

public void SwapInt(ref int lhs,ref int rhs)
{
int temp;
temp = lhs;
lhs = rhs;
rhs = temp;
}
public void SwapString(ref string lhs, ref string rhs)
{
string temp;
temp = lhs;
lhs = rhs;
rhs = temp;
}
view raw swap.cs hosted with ❤ by GitHub

Generics to the rescue. We've isolated the type as a form of abstraction (T) to act as a placeholder for the type we intend to use.

// Generic
public void Swap<T>(ref T lhs, ref T rhs)
{
T temp;
temp = lhs;
lhs = rhs;
rhs = temp;
}
view raw genericSwap.cs hosted with ❤ by GitHub

When the method is actually called, that placeholder is replaced with the type of the values used.

int a = 1;
int b = 2;
string aa = "Hello";
string bb = "World";
Swap<int>(ref a, ref b);
Swap(ref a, ref b); // we can even ignore being explicit about the type.
Swap(ref aa, ref bb);
view raw callIt.cs hosted with ❤ by GitHub

The value of Generics here is that it grants you productivity improvements, expressiveness and moves some safety concerns from execution time to compile time.

Note the two ways in which the method can be called. One with the type explicit, and the other implicit through type inference. The compiler is inferring the type parameters based on the method arguments you pass.

A generic is simply a placeholder for a type.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay