DEV Community

Sean
Sean

Posted on

Generics in C# (Part 3 - Generic Classes)

Introduction

This is the third part of my series on C# Generics (Part One, Part Two). In this article I will explain how to create Generic classes. To demonstrate this I will create a static class prints all items in a List using the InvariantCulture format.

One place where cultures differ is on DateTime. DotNet has an interface called IFormattable that implements a ToString() method that accepts a formatProvider. Using this interface and a Type constraint I will demonstrate how to print out IFormattables using Invariant culture in the static class InvariantCulturePrinter.

InvariantCulturePrinter

First, let's look at the static class InvariantCulturePrinter.

InvariantCulturePrinter

This is a Generic class which works in much the same way as the generic method in Part Two. The T's are replaced by the argument that is passed into the Type parameter. The main difference is the "where T : IFormattable". This is a Type constraint.

The PrintList() method uses a ToString() method that has two parameters. The first parameter is the stringFormat and the second parameter is the formatProvider. If this is a generic method that accepts any generic List as an argument, how can we be sure the argument will contain a type that supports this ToString(stringFormat, formatProvider) implementation?

That is where the type constraint comes in. IFormattable specifies the ToString(stringFormat, formatProvider) method. So specifying IFormattable as the Type constrain will ensure this ToString implementation is always available.

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay