Generic Programming in .NET

For most computers that run a Microsoft Windows operating system, the Microsoft .NET Framework is a good option for software development.

Prove you're a Dev Guru! Take the test now!

This framework has a huge library comprising of coded solutions for most day-to-day programming issues. It also uses a virtual machine that helps to execute programs by managing memory, providing a runtime environment and security. Language interoperability of the .NET Framework allows each language to utilise code written in other languages. We can define generic programming as a particular form of computer programming that helps develop efficient software libraries that developers can use later.

'Generic programming' is a rather vague concept. Various definitions of the term have been produced. The simplest one to understand is that generic programming hints at the functionality of a particular set of programming languages that allow some to refine a static type of system in an effective manner.

Here's an example. We can define a ‘template’ in C++ as a routine wherein a typical variable can have a number of parameters. Every combination of argument types occurring at a given moment has a unique template.

Generic programming can be very useful for developers, as it focuses on developing libraries of reusable components. Generics avoid code duplication, thus limiting the number of lines of code required. Being type-safe, errors are handled at the time of compiling. With generic programming, the level of abstraction is higher, factoring out details so that you can focus on a few concepts at a time.

The year 2005 witnessed the addition of generic programming into the .NET framework. Type erasure, however, is one aspect that .NET generics does not cover. .NET implements generic programming as a first class object, using reification in the runtime. To give an example:

Here, we hold a collection of a type that we create. Here is how we can define that class:

public class User

{

protected string name;

protected int age;

public string Name{get{return name;}set{name=value;}}

public int Age{get{return age;}set{age=value;}}

}

Here, we have defined the User. Let us create an instance of a .NET Framework Generic version of a simple List:

System.Collections.Generic.List users = new System.Collections.Generic.List();

We can progress further like this. Previous versions of the Common Language Runtime, as well as C#, had a number of limitations. For instance, in C#, one can achieve generalisation by casting types to and from the universal base type Object. This is not the case with generic programming. A developer can create a generic class, and thus create a collection that is surely type-safe at compile-time. Generic programming, by generalising software components, helps developers to reuse the components in a wide array of situations.