user3602030
user3602030

Reputation: 87

Practices value/reference memory in C#

Imagine we have this method:

// By value
private static void ShowMessage(string Message)
{
    Console.WriteLine("{0}", Message);
}

Is a good practise pass by value a string only if we want view/show the content?

For example, in a 32-bit system, a string with 20 characters (C# default: UTF-16) the reference is 32 bits, but by value is (20 characters * (2 bytes * 8 bits)) = 320 bits

32 bits vs 320 ...

Upvotes: 1

Views: 78

Answers (3)

Rafael Brasil
Rafael Brasil

Reputation: 232

I recommend you to use ref only when you need to change your variable content within the method:

private static void ShowMessage(ref string text){
    Console.WriteLine(text); // use the old content
    text= "this is the new value"; //the new variable content will override the old one
}

You can also use the out when the content will be written, but won't be read:

private static void ShowMessage(out string text){
    // you can't use the text variable, but you must set it's value
    text= "this is the new value"; //the new variable content will override the old one
}

In any other cases, you should use it as any other value variable. As the friends above have said, string is a Reference type in C#. It's the same of using the String (with upper S).

Upvotes: 2

Thomas Levesque
Thomas Levesque

Reputation: 292425

string is a reference type, so even if you pass it by value, it's a reference to the string that is passed, not a copy of the string. So the length of the string has no effect at all on what you pass to the method.

It's really important to understand the difference between value types and reference types, and between passing parameters by value or by reference. I suggest you read this article, which gives a good explanation.

Upvotes: 4

Jon
Jon

Reputation: 437366

You are not passing the whole string by value; string is a reference type, so what you are passing by value is a reference to the actual object.

"Reference" is an intentionally vague term in this situation. The implementation actually does pass a pointer to the instance.

Upvotes: 2

Related Questions