Generics in C# (Part 3 - Generic Classes)
Sean
Posted on April 7, 2019
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.
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.
Posted on April 7, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.