Value Or Reference? A C# Puzzle
Value Or Reference? A C# Puzzle
Written by Balamurugan Boominathan   
Article Index
Value Or Reference? A C# Puzzle


It doesn't work and its all due to the use of a value type within the foreach loop.

Because Product entity has been declared as struct which is value type  you can not directly update the Quantity property of a  Product entity which is being used as the iteration variable.

It even generates a compiler error message:

“Cannot modify p because it is foreach iteration variable.”

This doesn't happen if the Product entity is declared as a Class which is a reference type. In this case

p.Quantity = p.Quantity - Quantity;

will work because it modifies the object that p refers to rather than the value of p.

If you want to use a value type in a loop in this way you have to do the job more explicity and avoid using it as the loop variable.

For example:.

for (int i = 0; i < lstProducts.Count; i++)
Product p = lstProducts[i];
if (p.Name == ProductName)
p.Quantity = p.Quantity - Quantity;
lstProducts[i] = p;

In this case we have to retrieve the value type from the collection before we work on it.


The only real solution is to avoid using value types within sophisticated data structures. In other words, always prefer a class to a struct. This also avoids the potential problem of some future programmer converting your struct to a class thinking that it doesn't make any difference.


Further reading:

Inside C# 4 Data Structs

Value and Reference




blog comments powered by Disqus


To be informed about new articles on I Programmer, subscribe to the RSS feed, follow us on Google+, Twitter, Linkedin or Facebook or sign up for our weekly newsletter.

More Puzzles

Sharpen Your Coding Skills
Vertex Coverings And The Cool Kids Problem

Joe Celko has posed another puzzle that requires you to think like a programmer. This one asks us to find the cool kids in a social network - the ones who taken together know everyone else. This is al [ ... ]

Python Puzzle - Where Did The Time Go

A Python programming puzzle to get you up to speed. This one is all about time keeping, or is it? There are some strange things that go on in Python when you aren't paying attention. 

Sharpen Your Coding Skills
The Post Production Problem

Joe Celko has posed another puzzle that requires you to think like a programmer. This one is all about Post tag machines, which have absolutely nothing to do with mail of any type but a lot to do with [ ... ]

Other Articles






RSS feed of all content
I Programmer - full contents
Copyright © 2015 All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.