Home »
C#.Net
List<T>.Add() method with example in C#
C# List<T>.Add() method: Here, we are going to learn about the Add() method of List with example.
Submitted by IncludeHelp, on March 14, 2019
C# List<T>.Add() Method
List<T>.Add() method is used to add the object/element at the end of the list.
Syntax:
void List<T>.Add(T item);
Parameter: It accepts single an item of T type to add in the List.
Return value: It returns nothing – it's return type is void
Example:
int list declaration:
List<int> a = new List<int>();
adding elements:
a.Add(10);
a.Add(20);
a.Add(30);
a.Add(40);
a.Add(50);
Output:
10 20 30 40 50
C# Example to add items to the list using List<T>.Add() Method
using System;
using System.Text;
using System.Collections.Generic;
namespace Test
{
class Program
{
static void Main(string[] args)
{
//integer list
List<int> a = new List<int>();
//adding elements
a.Add(10);
a.Add(20);
a.Add(30);
a.Add(40);
a.Add(50);
//printing elements
Console.WriteLine("list elements are...");
foreach(int item in a)
{
Console.Write(item + " ");
}
Console.WriteLine();
//string list
List<string> b = new List<string>();
//adding elements
b.Add("Manju");
b.Add("Amit");
b.Add("Abhi");
b.Add("Radib");
b.Add("Prem");
//printing elements
Console.WriteLine("list elements are...");
foreach (string item in b)
{
Console.Write(item + " ");
}
Console.WriteLine();
//hit ENTER to exit
Console.ReadLine();
}
}
}
Output
list elements are...
10 20 30 40 50
list elements are...
Manju Amit Abhi Radib Prem