Making types safely reusable with generics
In 2005, with C# 2.0 and .NET Framework 2.0, Microsoft introduced a feature named generics, which enables your types to be more safely reusable and more efficient. It does this by allowing a programmer to pass types as parameters, similar to how you can pass objects as parameters.
First, let's look at an example of a non-generic type, so that you can understand the problem that generics is designed to solve.
- In the
PacktLibrary
project, add a new class namedThing
, as shown in the following code, and note the following:Thing
has anobject
field namedData
.Thing
has a method namedProcess
that accepts anobject
input parameter and returns astring
value.
using System; namespace Packt.Shared { public class Thing { public object Data = default(object); public string Process(object input) { if (Data == input) { return "Data and input are the same."; } else { ...