How To Use Generic Lists In C# – Made Easy

Generic lists in C# are a data structures that allow us to add and remove objects to store inside without declaring its size.

Andraz Krzisnik
How To Use Generic Lists In C# – Made...

Generic lists allow us to store various different objects inside much like arrays or array lists. However, this type of list is something we call a strongly typed list. It also gives you more options with extension methods from System.Linq namespace.

Apart from that, the difference between array lists and generic lists is that generic list has a specified data type, while array list doesn’t.

In general, we want to use lists whenever we’re working with a larger data collection that varies in size through time of application use.

For example, if we use an array, we can only specify its size at the time we declare it. Therefore, we’d need to set a large size and just not use the free space in it down the road. However, this wouldn’t be really great for the long term, because it’s an unnecessary contraint.

In order to give our datasets space to grow we can just use lists, where we can increase or decrease their size whenever necessary.

Generic lists in C#

We’ll briefly go over the basic methods for using these lists. I’d like to recommend you to check out the post I made about array lists. Furthermore, the methods I used in that guide apply to this tutorial as well.

Now let’s go over the code examples and see what’s what.

List<double> nums = new List<double>();
nums.AddRange(new double[]{ 2.0, 5.5, -3.2});
Console.WriteLine(string.Join('|', nums));

Console.WriteLine(string.Join('|', nums));

Console.WriteLine("Min number in list: " + nums.Min());
Console.WriteLine("Max number in list: " + nums.Max());
Console.WriteLine("Average number of list: " + nums.Average());

As you can see, using extension methods is fairly straight forward. Furthermore, we can use these methods to do all sorts of things like sorting or checking all objects at once. In case you want to explore the functionality of these methods more in depth, I suggest you visit Microsofts official documentation.


I hope this short guide helped you gain a better understanding on using generic lists in C#. I also suggest you check out my other posts about data structures in C#.

In case you want to check out how it works in practice you can also download the demo project I set up and try it out yourself.

Related Articles

Order-Statistic Filters

How To Make Midpoint Filter For Images – C# Guide

Midpoint filter is a order-statistic filter and we use it to process image data in spatial domain. This guide shows how to make it with C#.

Posted on by Andraz Krzisnik
Morphological Reconstruction

How To Make Opening By Reconstruction Work With C#

Opening by reconstruction is a morphological operation in image processing for removing small objects and recovering shape accurately after.

Posted on by Andraz Krzisnik