Talking about discoveries, I discovered something about C# today.
Let’s say I have a struct ‘MyStruct’ with an integer as its data member. and I create a list of this type.
List list = new List();
I add a few elements to this list.
list.Add(new MyStruct(10)); list.Add(new MyStruct(20));
If I try to modify any element in this list, that is when things become interesting.
list.m_age = 30;
The compiler starts its blaring sirens. Error: Cannot modify the return value of System.Collections.Generic.List<MyStruct>.this[int]’ because it is not a variable
This problem does not arise if you have a list of class instead of a structure. i.e, if I change MyStruct to a class (and call it MyClass to avoid confusion), this error message goes away. Why should it matter for structs and not for classes? I knew the basic difference between these two, one being a value type and the other being a reference type. This knowledge wasn’t enough to crack this puzzle.
A quick googling gave me the answer. The operator  is actually a function call. When you index a list and get the individual element, you are actually making a function call. You get the individual element as the return value of the function. This return value is placed on the stack and when you try to use the dot operator on this, you are actually trying to modify the return value of the function. i.e. you are modifying a copy of the element and your modifications will not affect the element in the list. The compiler, smart it is, catches this and informs you of the pitfall.
This does not affect a list of class items because class is a reference type. When you use  operator on a list of class, the  function is actually returning a reference to the original object and hence your modification on this reference object will cause the original element to change.
Phew! One discovery that was. Next time you are creating a list of structs, remember this little piece of information.
Beware! If you save the return value of the function in a variable, modify that variable and expect the actual list element to change, that’s not going to happen.
MyStruct s = list; s.m_age = 40; // This will not change the element list
Modifying the variable s is not going to modify list.
This poses an interesting question. Once you create a list of structs and initialize it, there is no way you can modify it? I need to find this out. Look out for more updates on this.