Back
Close

Demystifying C# Generics

AramT
13K views
Previous: Generics Interfaces Next: Conclusion

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`
·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
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants