0
0
CsharpHow-ToBeginner · 3 min read

How to Add Element to List in C# - Simple Guide

In C#, you add an element to a list using the Add() method of the List<T> class. For example, myList.Add(item); adds item to the end of the list.
📐

Syntax

The basic syntax to add an element to a list in C# is:

  • myList.Add(item);

Here, myList is your list variable, and item is the element you want to add. The Add() method appends the element to the end of the list.

csharp
List<T> myList = new List<T>();
myList.Add(item);
💻

Example

This example shows how to create a list of strings and add elements to it using Add(). It then prints all elements.

csharp
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<string> fruits = new List<string>();
        fruits.Add("Apple");
        fruits.Add("Banana");
        fruits.Add("Cherry");

        foreach (string fruit in fruits)
        {
            Console.WriteLine(fruit);
        }
    }
}
Output
Apple Banana Cherry
⚠️

Common Pitfalls

Some common mistakes when adding elements to a list include:

  • Trying to add elements to a list declared as var myList = new List<T>(); but forgetting to initialize it first (null reference error).
  • Using Add() on arrays instead of lists (arrays have fixed size).
  • Adding elements of the wrong type to a strongly typed list (compile-time error).

Example of a null reference error:

csharp
List<int> numbers = null;
numbers.Add(5); // This causes a runtime error because numbers is null

// Correct way:
numbers = new List<int>();
numbers.Add(5); // Works fine
📊

Quick Reference

Summary tips for adding elements to a list in C#:

  • Use Add() to append one element.
  • Use AddRange() to add multiple elements at once.
  • Always initialize your list before adding elements.
  • Lists are dynamic and can grow as needed.

Key Takeaways

Use the Add() method to add a single element to a List in C#.
Always initialize your list before adding elements to avoid null reference errors.
Add() appends the element to the end of the list, which grows dynamically.
Arrays cannot be resized; use List for dynamic collections.
AddRange() can add multiple elements at once if needed.