It has been long since I blogged on Evil Code series. Time to check one again now. Consider two samples of code.
Sample 1
public class AnotherClass { public MyClass ClassInstance{get;set;} } public class TestClass1 { public AnotherClass AnotherClass{get;set;} public int Id { get=> AnotherClass.ClassInstance.Id; set=> AnotherClass.ClassInstance.Id=value; } } public class MyClass { public int Id{get;set;} }
Sample 2
public class AnotherClass { public MyStruct StructInstance{get;set;} } public class TestClass2 { public AnotherClass AnotherClass{get;set;} public int Id { get=> AnotherClass.StructInstance.Id; set=> AnotherClass.StructInstance.Id=value; } } public struct MyStruct { public int Id{get;set;} }
How differently would two of the code samples given below behave ?
Well, Sample 1 compiles and Sample 2 doesn’t. Why ?? Sample 2, in fact raises following error.
Cannot modify the return value of 'AnotherClass.StructInstance' because it is not a variable
Could you reason why ?
If you look into the two Sample codes, there is a significant difference. MyStruct, used by Sample 2 is a value type. This means that when you are are in fact accessing a copy of StructInstance and not the valeu itself ( as you would have had it been a class – reference type).
Any change made in the property is made on the Copy instance, and then disregarded, leaving the original value unchanged.
This is the reason compiler warns you against.