References to value types...

Ian wrote a comment about being about to return references to value types.

Basically, he's asking for a way to build a collection of value types so that they can easily be modified, and to do this, he'd like the indexer to be able to return a reference rather than a value.

This restriction shows up from time to time, usually when somebody wants to write code like (example from Ian):

List<MyStruct> vec = new List<MyStruct>();
vec.Add(new MyStruct(10, 20));
vec[0].X += 1; // Error!

Because

vec[0]

gets a copy of the value stored at vec[0] and puts it in a temporary local, being able to modify the X property on that temporary copy is a useless thing to do, so the language prohibits it.

So why won't C# let you get the reference to a value? Well, it's all because of the presence of the garbage collector. If you had a reference (aka internal pointer) somewhere into the middle of an array, any movement of the array as part of a GC would mean that the reference would be invalid.

It might be possible to add a construct to a system that would say "this is an internal pointer, and if you move the outer object, you need to update the inner pointer as well, but that would mean that the reference to the value would not be a simple pointer, but a reference to another object which encapsulated the inner pointer (so the GC could find it), which pretty much defeats the purpose of being able to do this.

In C++, the programmer owns the memory, and gets to choose how things get created, deleted, and moved around. In C#, the GC owns the memory, and the programmer just gets to borrow it for a short period of time. Working in the C# world requires a different mindset, and until you internalize it, things are likely to seem a bit weird.

The meta message is around using structs in C#. In a word, don't use structs unless you're forced to use them - and by forced I mean that you need to do interop, or you've looked at your profiling data and realized that you really need to reduce the number of objects that you have around. In other words, they shouldn't be the default choice - there are a lot of disadvantages and gotchas with structs, though a few of those will go away when Whidbey shows up.

And if you do use structs, see if you can make them immutable. That hides most of the ugly cases.

Hope that makes sense