C# List – Add Element
List is a collection of elements. You can add one more elements to a given list. You have to make sure that the type of element matches the type of element in the list.
In this tutorial, we shall learn how to add an element to the list.
To add an element to the C# List, use List.Add() method. The definition of of List.Add() is given below.
void List<T>.Add(T item)
Add() method returns nothing. item/element passed as the argument to Add() method should match the type of List items.
Example 1 – Add Element to C# List
In this example, we shall shall create a List of integers, and then add items to it using Add() method.
Program.cs
using System;
using System.Collections.Generic;
class Program {
static void Main(string[] args) {
//empty list
List<int> nums = new List<int>();
//add elements to list
nums.Add(63);
nums.Add(58);
nums.Add(47);
//print list
foreach (int num in nums) {
Console.WriteLine(num);
}
}
}
Run the above C# program. The three items shall be added to the list.
Output
63
58
47
Example 2 – Add Object to C# List
In this example, we shall add custom class objects to the given list.
We shall define a class named Car. In the Main method, we shall create a List that can contain elements of type Car. Then we shall create objects of type Car and add to the list.
Program.cs
using System;
using System.Collections.Generic;
class Program {
static void Main(string[] args) {
//create list
List<Car> cars = new List<Car>();
//add objects to the list
cars.Add(new Car("Toyota", 1250000));
cars.Add(new Car("Tata", 1300000));
cars.Add(new Car("Honda", 1150000));
//print
foreach (Car car in cars) {
Console.WriteLine(car.name + " - "+car.price);
}
}
}
class Car{
public string name;
public int price;
public Car(string name, int price){
this.name = name;
this.price = price;
}
}
Run the above C# program.
Output
Toyota - 1250000
Tata - 1300000
Honda - 1150000
Example 3 – Add Element of Different Datatype to C# List
When you try to add an element of a different datatype, you will get an error saying argument cannot be converted.
In this example, we have initialized a list of integers. But, then we try to add an element of type string.
Program.cs
using System;
using System.Collections.Generic;
class Program {
static void Main(string[] args) {
//empty list
List<int> nums = new List<int>();
//add elements to list
nums.Add(63);
nums.Add(58);
nums.Add("hello");
//print list
foreach (int num in nums) {
Console.WriteLine(num);
}
}
}
Run the above C# program.
Output
D:\workspace\csharp\HelloWorld\Program.cs(10,18): error CS1503: Argument 1: cannot convert from 'string' to 'int' [D:\workspace\csharp\HelloWorld\HelloWorld.csproj]
Conclusion
In this C# Tutorial, we learned how to add an item to C# List, using List.Add() method.