#18:For vs ForEach Difference when looping through collection

You cannot  Add /Remove(Assign Values/Delete ) while you iterate Collection  with ForEach.

int[] a=new int[4]{1,2,3,4};
 foreach (int i in a)
 i = 7;// Error-Read Only Not Possible

Reason: IEnumerator has a method defined only with get,not with set.However you can add set method,but not preferred because it has its own side effects.

public object Current

get { throw new NotImplementedException(); } //Only get method,For Each can only read.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s