Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
foreach loop test in C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ForeachTest
{
public class Program
{
static void Main(string[] args)
{
List<int> lstValues = new List<int> { 1, 2, 3, 4, 5 };
foreach (int value in lstValues)
{
value = 2;//Compiler error, cannot assign to foreach iteration variable.
}
List<Customer> lstCustomer = new List<Customer>
{
new Customer("Steve"),
new Customer("Kevin"),
new Customer("Cook"),
new Customer("Finn"),
};
foreach (Customer objCustomer in lstCustomer)
{
Console.WriteLine(objCustomer.ToString());
objCustomer.Name = "Rohit"; //This is ok, objects is mutable.
objCustomer = null;//Compiler error, "cannot assign to foreach iteration variable."
lstCustomer.Remove(objCustomer);//Runtime exception, "Collection was modified; enumeration operation may not execute."
}
Console.ReadKey();
}
}
public class Customer
{
public string Name { get; set; }
public Customer(string name)
{
this.Name = name;
}
public override string ToString()
{
return Name;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.