Demystifying C# Generics

AramT
1,427 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

In .Net framework the collections namespace includes classes that represent collection of objects that include lists, queues, bit arrays, hash tables and dictionaries.

The namespace System.Collections.Generic is the generic version of System.Collection namespace. Using it, you can define strongly typed collections while gaining all benefits of generics (code reusability, type safety and better performance).

Let’s take the most commonly used Collection type which is the List. I will not be explaining about Collections now because it is outside the scope of this article.

So with generics, the List will have its parameter T, that you can pass to it whatever type you like and you will have a list of that type.

Check the below example, we are defining a list of floating points of type `float`
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
·using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;
namespace GenericsLesson
{
[TestClass]
public class GenericCollectionsTest
{
[TestMethod]
public void TestGenericList()
{
List<float> floatingPoints = new List<float>
{
1.3f,
2.6f,
99.8f,
34f
};
Assert.AreEqual(4, floatingPoints.Count);
Assert.AreEqual(1.3f, floatingPoints[0]);
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content