Skip to content

Instantly share code, notes, and snippets.

@gopigujjula
Created June 3, 2015 13:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gopigujjula/d98b62dc8dcba472342b to your computer and use it in GitHub Desktop.
Save gopigujjula/d98b62dc8dcba472342b to your computer and use it in GitHub Desktop.
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