foreach loop test in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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