NOTE: My code snippets are just snippets. They demonstrate an idea which can be adapted by you to solve your problem. They are not 100% complete and fully functional solutions equipped with error handling.
ldstr
Pushes a new object reference to a string literal stored in the metadata.
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.
Darwen.
www.pinvoker.com - PInvoker - the .NET PInvoke Interface Exporter for C++ Dlls.
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.
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
}
// If Pass strings from main to this function i will get local copies of s1 and s2
//instead of their references
How do you know you're getting local copies ?
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.
Last edited by darwen; July 13th, 2009 at 02:32 AM.
www.pinvoker.com - PInvoker - the .NET PInvoke Interface Exporter for C++ Dlls.
NOTE: My code snippets are just snippets. They demonstrate an idea which can be adapted by you to solve your problem. They are not 100% complete and fully functional solutions equipped with error handling.
Well, you need to use ref if you want the original reference instead of a copy. Reference types are always passed by reference, but that a copy of that reference is passed in by default (i.e., when you don't use the 'ref' keyword.)
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:
Code:
class Foo
{
public readonly int Id;
public readonly string Name;
public Foo( int id, string name )
{
Id = id;
Name = name;
}
}
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.
Bookmarks