How is a String type passed to a method or assigned to a variable in C #?

The String object behaves like a value type when using the == and! =, which means that the actual object is checked, not the link.

How about passing parameters, assigning and copying?

Passing string parameters: When a reference type is passed to a method, its reference is copied, but the underlying object remains the same.

Will this also be true for String type in C #? I mean, there are two pointers (messageVar and messageParam) pointing to the same object in the code below:

public static void main()
{
   string messageVar = "C#";
   Test(messageVar);

   // what about in assignement?
   string messageVar2 = messageVar;
}
public void Test(string messageParam)
{
// logic
}

How about assigning a variable? I would suggest that the link will be copied only, and the actual object will remain the same as in String Intern Pool. Not sure.

Will messageVar2 also reference the same object?

,

+5
4

, , , , , .

Object.ReferenceEquals(), , - :

static string messageVar = "C#";
public static void Main(string[] args)
{
    bool isSame = Test(messageVar); //true

    // what about in assignement?
    string messageVar2 = messageVar;
    isSame = Object.ReferenceEquals(messageVar2, messageVar);//also true
}

public static bool Test(string messageParam)
{
    // logic
    bool isSame = Object.ReferenceEquals(messageParam, messageVar);
    return isSame;
}
+3

" == ! =, , , ."

String ( ) . , == != ( ) , ; . String.Equality String.Inequality.

( , String).

+2

.

string , : , , . . , , : , ( ref out), .

0

All Articles