I understand string is reference type.
string s;
Is "s" pointing a stack or heap object ?
Printable View
I understand string is reference type.
string s;
Is "s" pointing a stack or heap object ?
All reference types live on the heap. Only value types live on the stack, though value type will live on the heap if you box it (cast it to object).
You will be implicitly :
compiles to (in IL)Code:string s = "hello";
If you look in the docs it says thatCode:.locals init (
[0] string s)
L_0000: nop
L_0001: ldstr "hello"
L_0006: stloc.0
So "hello" is stored in the metadata of the assembly, but the ldstr instruction creates a reference to a string object (i.e. on the heap) from this metadata.Quote:
ldstr
Pushes a new object reference to a string literal stored in the metadata.
Darwen.
I have the question in same line
then why reference of string is not passed to any of my function
ie
code:
public static void swap(string s1, string s2)
{
// If Pass strings from main to this function i will get local copies of s1 and s2
//instead of their references
}
code:
Any help is appreciated
Thanks in advance.
if you want to pass a reference as paramater, you need to add the 'ref' modifier.
Code:public static void swap(ref string s1, ref string s2)
{
...
}
How do you know you're getting local copies ?Quote:
// If Pass strings from main to this function i will get local copies of s1 and s2
//instead of their references
Actually you're not getting local copies, you're getting references. The strings are passed by reference. Because System.String is a class which are always passed by reference in .NET - that's why they are called 'reference types'.
But System.String is peculiar in that it is an immutable class i.e. it exposes no methods which allow you to change the contents of the class once it's been created. Hence it behaves like a value type, but in fact is a reference type.
That's probably why you think you're getting a local copy - you aren't, you are just getting references to instances of string which you can't change.
Darwen.
So, what happens in s1 = s2 ?Code:string s1 = "first string";
string s2 = "second string";
s1 = s2;
- Is that the address of s2 copied to s1 (Shallow copy)?
- Copy the entire contents (deep copy) ?
- or What ?
They are references, so the reference is copied to s1;
Thank you BigEd781.
May I know what makes it immutable.
may be the keyword "sealed" which dont allow you to inherit the string class further ?
No, it is immutable simply because the class gives you no way to change its member data. Look at this class:
That class is immutable. You pass some data into the constructor, the data is set, and now there is no way that it can be changed by the outside world.Code:class Foo
{
public readonly int Id;
public readonly string Name;
public Foo( int id, string name )
{
Id = id;
Name = name;
}
}