Click here to Skip to main content
15,896,557 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
string is a reference type,How can I change its value from another object as array for example

Array:
C#
var numbers = new int[] {1,2,3};
var numbers2 = numbers;
numbers2[0] = 9;
Console.WriteLine(numbers[0]); //Output is:9 because arrays is a rference type


What I have tried:

String:
C#
var numbers = new string(new char[]{'o','n','e'});
var numbers2 = numbers;
numbers2 = "two";
Console.WriteLine(numbers); //why the output here is "one" it should be "two" it is a reference type??!!
Posted
Updated 6-Aug-16 0:14am
v5
Comments
Ralf Meier 6-Aug-16 4:59am    
I can't give you a scientifical explanation - but your second example/code is an assignment and not a referencing.
Strings, Integer, Single, Double and so on are objects - but also base-types. Base-types normally assign their value and don't reference it ..

1 solution

Because...string is a reference type! :laugh:
Have a look at the start of this: Using struct and class - what's that all about?[^] it explains teh difference, and what is going on when you assign references. (You might want to skip the last half for the moment, it gets a bit busy for beginners).

Once you've had a good read it will hopefully make sense, and then you can explain exactly what you are trying to do and I'll try to explain how to do it.
 
Share this answer
 
Comments
moh_mou 6-Aug-16 6:38am    
I modified the code to be more clear. I can't get a clearly reason for that :(
OriginalGriff 6-Aug-16 8:16am    
Read the article again: an int is value type, a string is a reference type, an array of any type is a reference type.
When you copy a value type you copy the value.
When you copy a reference type you copy the reference.
So when you copy the reference to the array in the first code, both numbers and numbers2 are "pointing" at the same data - modify one, and it affects the data they both use.
When you copy the reference in the second code, you copy the reference to the string data, not the variable itself. You then overwrite one of the references but that doesn't affect the other because it is not the same variable.
With value types, the variable *IS* the data - with reference types the variable is a "pointer" to the data, not the data itself.
Your second piece of code is not the same as the first, it's the equivelant of:
var numbers = new int[] {1,2,3};
var numbers2 = numbers;
numbers2 = new int[] {4, 5, 6};
numbers2[0] = 9;

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900