Making Types Safely Reusable with Generics
Learn about transitioning from non-generic to generic types, which enhance type safety, reusability, and performance.
We'll cover the following
In 2005, with C# 2.0 and .NET Framework 2.0, Microsoft introduced a feature named generics, enabling our types to be more safely reusable and efficient. It allows a programmer to pass types as parameters, like how we can pass objects as parameters.
Working with non-generic types
First, let’s look at an example of working with a non-generic type so that we can understand the problem that generics are designed to solve, such as weakly typed parameters and values, and performance problems caused by using System.Object
.
System.Collections.Hashtable
can be used to store multiple values, each with a unique key that can later be used to quickly look up its value. Both the key and value can be any object because they are declared as System.Object
. Although this provides flexibility when storing value types like integers, it is slow, and bugs are easier to introduce because no type checks are made when adding items. Let’s write some code:
Step 1: In Program.cs
, create an instance of the non-generic collection, System.Collections.Hashtable
, and then add four items to it, as shown in the following code:
Get hands-on with 1400+ tech skills courses.