Generics in C# (Part 3 - Generic Classes)

seantwie03

Sean

Posted on April 7, 2019

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.

💖 💪 🙅 🚩
seantwie03
Sean

Posted on April 7, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

PureScript for Scala developers
scala PureScript for Scala developers

November 30, 2024

AssertionError: 403
drf AssertionError: 403

November 28, 2024

Designing a Covariant Generic Type in C#
undefined Designing a Covariant Generic Type in C#

November 27, 2024

Understanding Variance in C#
csharp Understanding Variance in C#

November 27, 2024