What is the difference between assigning a value to an index of an array and assigning a value to the alias of the index of an array?
public string[] arrTestResults = new string[8];
public string TestName;
[TestInitialize]
public void SetupTest()
{
// Assigning aliases to array indexes
TestName = arrTestResults[0] = "";
}
public void General()
{
arrTestResults[0] = "Test 1: General"; // works
TestName = "Test 1: General"; // does not work. Quick Wat开发者_开发百科ch says TestName = Null. WHY?
I think your question title shows the potential misunderstanding here:
the alias of the index of the array
When you assign a string like so:
TestName = arrTestResults[0];
You're NOT assigning an alias to what's contained in arrTestResults[0]
, rather, you're copying the reference to the string arrTestResults[0]
is pointing to into TestName
. This is a copy of the reference to a string, but not an alias.
Later, when you assign a value to TestName
:
TestName = "Test 1: General";
This copies a new reference, overwriting the old one. It does nothing to the reference in the array, as that's a separate copy.
TestName
is NOT an alias to arrTestResults[0]
.
I'm assuming that arrTestResults
is string[]
and that TestName
is too.
arrTestResults[0]
is a storage location whose value refers to an instance of string
.
TestName
is a storage location whose value refers to an instance of string
.
TestName = arrTestResults[0] = "";
does not make TestName
an alias for arrTestResults[0]
. Instead, it assigns to the storage location TestName
and to the storage location arrTestResults[0]
a reference to an instance of string
that is equal to ""
. That is, there is a reference to ""
. That reference is assigned to arrTestResults[0]
and to TestName
. It is quite similar to
int y = 0;
int x = y = 17;
Here, x
is NOT an alias for y
. We have just copied the value 17
to y
and to x
. In our case, the value is the reference. A reference to ""
is copied to arrTestResults[0]
and to TestName
.
Then
arrTestResults[0] = "Test 1: General";
assigns a new reference to the storage location arrTestResults[0]
.
It's quite like
y = 42;
And then
TestName = "Test 1: General";
assigns a new reference to the storage location TestName
. It does not alter the value of arrTestResults[0]
because these two storage locations are different. Again, this is quite like
x = 69;
This does not alter the value of y
.
That's not an alias; it's an independent variable.
It is not possible to make a variable that is an alias to another variable or to an array element (unless you use unsafe code).
精彩评论