I am not exactly sure what you're asking but I think your confusion is about reference and value types.
If you want to write to string1
and string2
using myArray
you have to know a thing or two about value and reference types in C#.
For your current usage you can consider string a value type. With this I mean: that if you assign a string to another string (string stringX = a_previous_declared_String
) it creates a copy. Changing the copy will not change the original. Storing your string in MyArray
also creates a copy.
(Please note that in fact string is a reference type which behaves like a value type when doing assignment (stringX = stringY
) operations. If you want to know more, you can e.g. start here. For the purpose of explaining the general difference between value types and reference types, using your example, I simplify an call string a value type here).
If you want to change the original, you have to store a reference to your string in myArray
. For this, in C#, you can create a reference type variable which holds your value type. This can be a class which holds your string as a field. Then, you store a reference to your class in MyArray
. If you then change the string via MyArray
, your original string1
and string2
wil also get modified.
I created the simplest version of this to help you understand. See @knittl his answer for a more general implementation that would work for other value types (like int
and float
) as well.
My example (which I tested and runs as C# console application):
using System;
namespace TestProgram
{
public class RefTypeString
{
public string MyString;
public RefTypeString(string myString)
{
MyString = myString;
}
}
class Program
{
static void Main(string[] args)
{
RefTypeString string1 = new RefTypeString(null);
RefTypeString string2 = new RefTypeString("initial value");
RefTypeString[] myArray = { string1, string2 };
for (int i = 0; i < myArray.Length; i++)
{
if (i == 0)
{
myArray[i].MyString = "hello!"; //set value for string1 and string2 not an array
}
}
Console.WriteLine("MyArray[0] / string1");
Console.WriteLine(myArray[0].MyString);
Console.WriteLine("MyArray[1] / string1");
Console.WriteLine(myArray[1].MyString);
Console.WriteLine("string1");
Console.WriteLine(string1.MyString);
Console.WriteLine("string2");
Console.WriteLine(string2.MyString);
}
}
}
Console output:
MyArray[0] / string1
hello!
MyArray[1] / string1
initial value
string1
hello!
string2
initial value