Sharing a lesson...
-
Not a question, but something I learnt today that I'd like to share ;). If I declare and initialise as follows...
string[] a,b,c; a = b = c = new string[size];
a, b, and c all share the same memory location (i.e if you alter b - c and a are affected the same). Something I should have spotted, but is all so easy to overlook with these fancy new languages. :).Mark Brock "We're definitely not going to make a G or a PG version of this. It's not PillowfightCraft." -- Chris Metzen Click here to view my blog
-
Not a question, but something I learnt today that I'd like to share ;). If I declare and initialise as follows...
string[] a,b,c; a = b = c = new string[size];
a, b, and c all share the same memory location (i.e if you alter b - c and a are affected the same). Something I should have spotted, but is all so easy to overlook with these fancy new languages. :).Mark Brock "We're definitely not going to make a G or a PG version of this. It's not PillowfightCraft." -- Chris Metzen Click here to view my blog
Exactly, because arrays in C# are reference types.
-
Not a question, but something I learnt today that I'd like to share ;). If I declare and initialise as follows...
string[] a,b,c; a = b = c = new string[size];
a, b, and c all share the same memory location (i.e if you alter b - c and a are affected the same). Something I should have spotted, but is all so easy to overlook with these fancy new languages. :).Mark Brock "We're definitely not going to make a G or a PG version of this. It's not PillowfightCraft." -- Chris Metzen Click here to view my blog
Someone might be mislead to believe that...
string[] a, b, c; a = b = c = new string[size];
would behave the same as...int a, b, c; a = b = c = 10;
...which (as you discovered) it doesn't.MarkBrock wrote:
but is all so easy to overlook with these fancy new languages
...easy to overlook because it is poor style and easily misleading. To clearly show your intentions, it would have been better coded as either:
string[] a = new string[size];
string[] b = a;
string[] c = a;or
string[] a = new string[size];
string[] b = new string[size];
string[] c = new string[size];...depending on what your intentions are.