...

/

Making Types Safely Reusable with Generics

Making Types Safely Reusable with Generics

Learn about transitioning from non-generic to generic types, which enhance type safety, reusability, and performance.

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, ...