Understanding C# generics much better

Viewed 24802

I looked at some sample code using C# generics. Why and when should I use them?

All the examples were complex. I need a simple, clear example that gets me started with C# generics.

5 Answers

I have a use case here from Matt Milner, instructor at LinkedIn Learning. It's a little verbose, not simple as you requested, but I found it useful for diving deeper on why generics are necessary.

Generics Over Value and Reference Types (on C#)

  • Value Types: bool, byte, char, decimal, double, enum, float, int, long, sbyte, short, struct, uint, ulong, ushort.
  • Reference Types: String, Arrays (even if their elements are value types), Class, Delegate.

Part 1: On Value Types

Let's say you have this method:

static void Swap(object first, object second)
{
    object temp = second;
    second = first;
    first = temp;
}

And you use it like so:

int x = 5, y = 7;
Swap(x, y);
System.Console.WriteLine($"X: {x} and Y: {y}");

Which prints out:

X: 5 and Y: 7

No swap here. Why? Because:

  • int are value types.
  • So, when they go into the method, and out, they have different scope. They've been just "copied by value" and not "by reference".
  • Note: C# allows treating int types as objects, but this involves doing boxing and unboxing. Keep in mind this is an expensive operation at memory level.

Should this problem be solved by using reference types? Let's try it out.

Part 2: On Reference Types

We are going to use a custom class, previously defined in some library:

var p1 = new Person
{
    FirstName = "Matt",
    LastName = "Milner"
};

var p2 = new Person
{
    FirstName = "Amanda",
    LastName = "Owner"
};

Let's swap them.

Swap(p1, p2);
System.Console.WriteLine($"Person 1 is: {p1.FirstName}");

We should read, Amanda, but we get instead:

Person 1 is: Matt

Why? Usually we would expect the change to occur, since class instances are passed by reference. But this is not the case, because we are in fact passing a copy of the address to the temp instance.

What if we modify the method with ref?

Part 3: Using ref?

static void Swap(ref object first, ref object second)
{
    object temp = second;
    second = first;
    first = temp;
}

This should allow us to change not just the parts of the object, but also what they point to.

Swap(ref p1, ref p2);
System.Console.WriteLine($"Person 1 is: {p1.FirstName}");
  • This won't work. Why?
  • Because you can't convert from a ref of Person to a ref of Object. They're too unlike types.
  • You'll read a compilation error from the compiler before even running the program.

Part 4: Using Generics

  • This problem is solved with generics.
  • They can be used with any given type (int, arrays, etc) without stepping in into these problems.
static void Swap<T>(ref T first, ref T second)
{
    T temp = second;
    second = first;
    first = temp;
}
  • Here we have a T parameter, generic or "Type" parameter.
  • T replaces completely the Object declarations in the method, and allows to tell to the method what we are putting in it when it is used. Like so:
Swap<Person>(ref p1, ref p2);
Swap<int>(ref x, ref y);

System.Console.WriteLine($"Person 1: {p1.FirstName}");
System.Console.WriteLine($"X: {x} and Y: {y}");

Which prints out:

Person 1 is: Amanda
X: 7 and Y: 5

Summing Up

  • For both reference and value types:
static void Swap(object first, object second); // No swap
static void Swap(ref object first, ref object second); // No swap
static void Swap<T>(ref T first, ref T second); // Swap
  • This specifies dynamically the type for the method.
  • At compile time, the calling code provides/informs the type is being used.

Note: I still need to check myself why the reference type behave this way, which as far as I know it is related to how object memory addresses are passed, referenced and copied. For the most part I just followed along the explanation from Matt Miller.

Related