The code below compiles, but I don’t understand the behavior of keeping the 1 element array instead of assigning the two element array. Is there a name for this behavior so that I could search for more information about it? I realize that this code isn’t sensible because the 2 byte array could be assigned in the call to the constructor in GetData.
using System;
public class Item
{
public Item(string name, byte[] data)
{
Name = name;
Data = data;
}
public string Name { get; set; }
public byte[] Data { get; set; }
}
public class Test
{
Item member;
public Test()
{
member = new Item("name0", new byte[1]);
}
public static void Main()
{
Test test = new Test();
test.member.Data = test.GetData();
Console.WriteLine("name={0} array={1}", test.member.Name, test.member.Data.Length);
}
public byte[] GetData()
{
member = new Item("name1", new byte[1]);
return new byte[2];
}
}
Here’s what’s happening:
new Test(), a new Item (let’s call it object a) is created in the constructortest.memberis evaluated. This will return object a.test.GetMember()is called, in which:memberis re-assigned a new Item object (we’ll call it object b)test.memberhas a reference to object b (due to step 3.1)This can appear confusing. As far as naming this behavior, it’s all just the evaluation order of statements. The programming technique to avoid this is to not cause side effects in your “Get” methods; get methods should only return values, not change the data of the object.