String. Value-like behaviour of object | Sololearn: Learn to code for FREE!
0

String. Value-like behaviour of object

Is "string" a value or reference type? Why it's behavior doesn't look like reference type variable? On the one hand, "When you declare a string variable, you basically instantiate an object of type String". Objects of some class are reference types and the following code will write "22". ... class Test { public string v; } ... Test a = new Test(); a.v = 1; Test b = a; b.v = "2"; Console.WriteLine (a.v+b.v); ... On the other hand, behavior of "string" variable doesn't look like reference type, so the following code will write "12". ... string a = "1"; string b = a; b = "2"; Console.WriteLine(a+b); ...

2nd Apr 2017, 11:29 AM
Denis
2 Answers
+ 1
For easy life, think of it as a value type. The string type is handled exceptionally in C# and many other programming languages. It is immutable, which means, that it has no inner values modifiable unless creating another string, acts exactly like number types, like integer. When using it imagine how the type 'int' would act in such situation; string will work the same. In your example code not the string member 'Test.v' acts like an object, but the 'Test' objects themselves. Which makes a perfect sense. You share one object on two references 'a' and 'b', so when you modify 'b. v' it modifies 'a.v' too, because 'a' and 'b' is the same 'Test' object. Knowing this, you only initialited one variable with the type string. In the second code, you initialite two of them. Huge difference :) Note: 'string a = 1;' won't work without ["] marks. More on the 2nd situation ... replace string with int and you will see: 'b' gets the value of 'a', but not as a reference. It's value is copied, the same way as number values are copied upon using 'x = y' statements. Hope I helped! :)
7th Apr 2017, 12:40 PM
Magyar Dávid
Magyar Dávid - avatar
+ 1
Thanks a lot! that's became crystal clear for me now)
10th Apr 2017, 4:47 AM
Denis