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
How to declare and initialize a list in C#?
A List in C# is a generic collection that stores elements in a resizable array. You can declare and initialize a List in several ways, depending on whether you want to add elements immediately or start with an empty collection.
Syntax
Following is the basic syntax for declaring a List −
List<dataType> listName = new List<dataType>();
Following is the syntax for initializing a List with values −
List<dataType> listName = new List<dataType>() {
value1,
value2,
value3
};
Empty List Declaration
To declare an empty List that you can add elements to later −
using System;
using System.Collections.Generic;
class Program {
static void Main() {
List<string> myList = new List<string>();
myList.Add("one");
myList.Add("two");
myList.Add("three");
Console.WriteLine("List count: " + myList.Count);
foreach (string item in myList) {
Console.WriteLine(item);
}
}
}
The output of the above code is −
List count: 3 one two three
List Initialization with Values
You can declare and initialize a List with values in one statement using collection initializer syntax −
using System;
using System.Collections.Generic;
class Program {
static void Main() {
List<string> myList = new List<string>() {
"one",
"two",
"three",
"four",
"five",
"six"
};
Console.WriteLine("List count: " + myList.Count);
foreach (string item in myList) {
Console.WriteLine(item);
}
}
}
The output of the above code is −
List count: 6 one two three four five six
Different Data Types in Lists
Lists can store different data types. Here's an example with integers −
using System;
using System.Collections.Generic;
class Program {
static void Main() {
List<int> numbers = new List<int>() { 10, 20, 30, 40, 50 };
Console.WriteLine("Integer list:");
foreach (int num in numbers) {
Console.WriteLine(num);
}
List<bool> flags = new List<bool>() { true, false, true };
Console.WriteLine("\nBoolean list:");
foreach (bool flag in flags) {
Console.WriteLine(flag);
}
}
}
The output of the above code is −
Integer list: 10 20 30 40 50 Boolean list: True False True
Common List Methods
| Method | Description |
|---|---|
| Add(item) | Adds an element to the end of the list |
| Count | Gets the number of elements in the list |
| Remove(item) | Removes the first occurrence of the specified element |
| Clear() | Removes all elements from the list |
Conclusion
Lists in C# provide a flexible way to store collections of data with dynamic sizing. You can declare an empty List and add elements later, or initialize it with values using collection initializer syntax. Lists are strongly typed and support various data types like strings, integers, and booleans.
