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

Solution

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.

Pattern

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.

 csharp

Further reading:

Inside C# 4 Data Structs

Value and Reference

 

Banner

espbook

 

Comments




or email your comment to: comments@i-programmer.info

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

More Puzzles

C#
In-Place Or Operator Methods?

This particular C# puzzle is one of those that involves an error that no self respecting programmer would make... but are you so sure. If you use the DateTime class regularly then sure, you not only w [ ... ]


Sharpen Your Coding Skills
The Best Sub-Array Problem

At first glance this puzzle seems trivial, all you have to do is find a sub-array, in an array of numbers,  that sums to the largest value. It sounds almost too easy to need a solution, let alone [ ... ]


Javascript
Stringy Objects

A Programmer's Puzzle in which we contemplate situations in which string equivalence in Javascript is clearly not what it seems - and explain why it all goes wrong.


Other Articles