Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Adding an element to the List in C#
The List<T> class in C# provides the Add() method to add elements to the end of the list. This method is part of the System.Collections.Generic namespace and allows you to dynamically grow the list by appending new elements.
Syntax
Following is the syntax for adding an element to a List −
list.Add(element);
Parameters
- element − The object to be added to the end of the List<T>. The value can be null for reference types.
Adding String Elements to List
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(String[] args) {
List<String> list = new List<String>();
list.Add("One");
list.Add("Two");
list.Add("Three");
list.Add("Four");
list.Add("Five");
list.Add("Six");
list.Add("Seven");
list.Add("Eight");
Console.WriteLine("List elements:");
foreach (string item in list) {
Console.WriteLine(item);
}
}
}
The output of the above code is −
List elements: One Two Three Four Five Six Seven Eight
Adding Integer Elements to List
using System;
using System.Collections.Generic;
public class Demo {
public static void Main(String[] args) {
List<int> list = new List<int>();
list.Add(50);
list.Add(100);
list.Add(150);
list.Add(200);
list.Add(250);
list.Add(500);
list.Add(750);
list.Add(1000);
Console.WriteLine("List contains " + list.Count + " elements:");
for (int i = 0; i < list.Count; i++) {
Console.WriteLine("Index " + i + ": " + list[i]);
}
}
}
The output of the above code is −
List contains 8 elements: Index 0: 50 Index 1: 100 Index 2: 150 Index 3: 200 Index 4: 250 Index 5: 500 Index 6: 750 Index 7: 1000
Adding Custom Objects to List
using System;
using System.Collections.Generic;
class Student {
public string Name { get; set; }
public int Age { get; set; }
public Student(string name, int age) {
Name = name;
Age = age;
}
public override string ToString() {
return Name + " (Age: " + Age + ")";
}
}
public class Demo {
public static void Main(String[] args) {
List<Student> students = new List<Student>();
students.Add(new Student("Alice", 22));
students.Add(new Student("Bob", 24));
students.Add(new Student("Carol", 23));
Console.WriteLine("Student list:");
foreach (Student student in students) {
Console.WriteLine(student);
}
}
}
The output of the above code is −
Student list: Alice (Age: 22) Bob (Age: 24) Carol (Age: 23)
Conclusion
The Add() method in C# provides a simple way to add elements to the end of a List<T>. It works with any data type and automatically increases the list capacity as needed, making it an efficient choice for dynamic collections.
Advertisements
