In this blog post, we will see how easily we can add items to a list in C#.
At the time of writing this post, we are using the latest version of ASP.NET i.e. .NET 6.
Why Add Items To List In C#?
A list represents a collection of strongly typed objects.
This can be a list of integers, a list of strings, or a list of complex types.
A list in C# is an easy way to maintain a collection of similar types and then using the functions that C# provides you can easily iterate on that list if you need to.
There will be numerous use cases when you would need to add a new item to a list dynamically.
For example, if you have a list of years that are from 2000 to 2020, now it's time to add the next 10 years to that list. You would need to dynamically add items to the list so that you can use them.
Let's see how you can do it.
Adding Items To A New List In C#
In this example, we will see two ways we can create a new list and add items to the list.
Method 1 - Creating A New List And Adding Items In The Same Line
In the above example, we are creating a new list of integers and also adding default items to the list in the same line.
If you know the default items of the list, this is an easy way to do it.
Method 2 - Create New List And Add Items In A Separate Line
Let's say we have an existing list of numbers, from 1 to 5, and we need to add a new number to the existing list, we will do that using the ".Add" method that is provided to a list and we will provide the new number to this "Add" method as a parameter.
As you can see in the image above, we are adding items to the integer list in a separate row and after the declaration and instantiation.
Add String Items To List In C#
Similar to what we saw in the examples above, the same theory applies to any other type in C#.
As you know list accepts a similar type, apart from integers they can also take strings.