Moti
Moti

Reputation: 927

C# Save reference to string variables in array

I would like to save a reference to strings in array. For example:

string x = "x", y="y", z="z";
string array[];

I would like that array will save a reference to x,y,z. so, in case I will change the array[0] to "xx" then the x will include the "xx"

Thanks Moti

Upvotes: 3

Views: 3232

Answers (5)

Massimiliano Uguccioni
Massimiliano Uguccioni

Reputation: 151

By Reading the comment I reached goal :)

backuping the Enemy Last Know Position... actually I'm doing it on this way. If you have a better solution, show it ^_^

    if (EnemyLKP != EnemyLKPBackup[2])
        {
            EnemyLKPBackup[1] = EnemyLKPBackup[2];
            EnemyLKPBackup[0] = EnemyLKPBackup[1];
            EnemyLKPBackup[2] = EnemyLKP;
        }

Upvotes: 0

Sandeep Shankar
Sandeep Shankar

Reputation: 81

A string variable in C# is immutable. But a StringBuilder variable is mutable.

StringBuilder sb_x = new StringBuilder("x");
StringBuilder sb_y = new StringBuilder("y");
StringBuilder sb_z = new StringBuilder("z");

StringBuilder[] array = { sb_x, sb_y, sb_z };
array[0].Append("x");

Now array[0] = "xx" and sb_x is also "xx"!

Upvotes: 2

zmbq
zmbq

Reputation: 39013

It can't be done. Strings in C# are immutable, meaning you can't change them at all, you can only change string references. And you can't create an array of string references (unless you resort to unsafe code - don't go there).

You need to use some other structure to hold your data. A Dictionary<string, string> is a possibility as someone suggest. Or, you can always access the strings through your array.

Upvotes: 0

Rahul
Rahul

Reputation: 16335

There are two kinds of types in the C# type system "value types" and "reference types".

Value types are copied by value. when you copy one, you get an entirely new object.

Reference types are copied by reference. when you copy one, you are actually copying a reference to some storage location.

String is a value type, but you're trying to make it behave like a reference type.

You can create a class with a String property and then use an array of that class:

public class StringWrapper
{
    public String Value {get; set;}
}

Then you can use it like this:

public class SomeOtherClass
{
   public void SomeMethod()
   {
       StringWrapper[] array = new StringWrapper[3];
       var x = new StringWrapper() { Value="X"; }
       var y = new StringWrapper() { Value="y"; }
       var z = new StringWrapper() { Value="z"; }

       array[0] = x;
       array[1] = y;
       array[2] = z;

       array[0].Value = "xx";
   }
}

If you change x.Value, then array[0].Value will also change.

Upvotes: 1

Greg Oks
Greg Oks

Reputation: 2730

Maybe try using

Dictionary<string,string> 

instead:

http://www.dotnetperls.com/dictionary

Upvotes: 0

Related Questions