A good experience

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.

 
1List list = new List();

I add a few elements to this list.

1list.Add(new MyStruct(10));
2list.Add(new MyStruct(20));

If I try to modify any element in this list, that is when things become interesting.

1list[0].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.

Update:

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.

1MyStruct s = list[0];
2s.m_age = 40; // This will not change the element list[0]

 

Modifying the variable s is not going to modify list[0].

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值