c-sharp
  1. c-sharp-list

C# List

In C#, a list is a collection of elements of the same type that can be dynamically resized. Lists are useful for storing and manipulating data in a flexible and efficient way. In this tutorial, we'll discuss how to create and use lists in C#.

Syntax

The syntax for creating a list in C# is as follows:

List<type> listName = new List<type>();

where "type" is the data type of the elements in the list, and "listName" is the name of the list.

Example

Let's say we want to create a list of strings containing the names of fruits. Here's how we can implement it:

List<string> fruits = new List<string>();
fruits.Add("Apple");
fruits.Add("Banana");
fruits.Add("Orange");

Now, we can use the list in our code:

Console.WriteLine("List of Fruits:");
foreach (string fruit in fruits) {
   Console.WriteLine(fruit);
}

Output

When we run the example code above, the output will be:

List of Fruits:
Apple
Banana
Orange

This is because we created a list of strings containing the names of fruits, added some values to it, and printed them to the console.

Explanation

In the example above, we created a list of strings called "fruits". We then added some string values to it using the Add method. Finally, we printed the values of the list to the console using a foreach loop.

Use

Lists are useful for storing and manipulating data in a flexible and efficient way. You can use lists to create dynamic collections of elements that can be sorted, filtered, and searched. Lists also provide methods to add, remove, and modify elements in the list.

Important Points

  • Lists are dynamically resizable and can change in size as elements are added or removed.
  • Lists can contain generic types, such as List, List, List, etc.
  • Lists are indexed starting at 0, so the first element in the list has an index of 0.
  • List is a class in C# that provides a variety of methods to manipulate lists.

Summary

In this tutorial, we discussed how to create and use lists in C#. We covered the syntax, example, output, explanation, use, and important points of lists in C#. With this knowledge, you can now use lists in your C# code to store and manipulate data in a flexible and efficient way.

Published on: