String object behaves like a Value type when using == and != operators which means the actual object rather than the reference is checked.
What about parameter passing, assignments and copying?
String Parameter Passing:
When a reference type is passed to a method, its reference is copied but the underlying object stays the same.
Would this also be true about String type in C#? I mean would there be 2 pointers (messageVar and messageParam) pointing to the same object in the below code:
public static void main()
{
string messageVar = "C#";
Test(messageVar);
// what about in assignement?
string messageVar2 = messageVar;
}
public void Test(string messageParam)
{
// logic
}
What about when it’s assigned to a variable? I’d guess, the reference would be copied only and the actual object stays the same cached in the String Intern Pool. Not sure.
Would messageVar2 also refers to the same object?
Thanks,
Yes, you are correct only references are copied, the object instance referenced is one and the same.
You can easily verify this using
Object.ReferenceEquals()to test if two references point to the same object instance – I modified your example a bit to show this: