Passing String or StringBuilder to Function in C# (By Value or By Reference)


What happens if you pass a string type to a function? Does it pass by value or reference? What happens if you pass StringBuilder?

In C#, the string is a very special class that is passed by reference In C#, string is a reference type but it is passed by value. You can also use the Alias type String. Other primitive data types are similar, for example, int and Int32, they are all passed by values at default.

The following fails to change the value because s is passed by value (same if you use string).

1
2
3
4
        static void processString(String s)
        {
            s = "changed";
        }
        static void processString(String s)
        {
            s = "changed";
        }

To pass by reference, use something like this:

1
2
3
4
5
6
        static void processString(ref String s)
        {
            s = "changed";
        }
 
// processString(ref x);
        static void processString(ref String s)
        {
            s = "changed";
        }

// processString(ref x);

The keyword ref is required for both function parameters and function caller.

However, other classes, you can skip the keyword ref and they will be passed by reference, for example,

1
2
3
4
5
6
7
        static void processStringBuilder(StringBuilder sb)
        {
            sb.Clear();
            sb.AppendLine("changed");
        }
 
// processStringBuilder(x);
        static void processStringBuilder(StringBuilder sb)
        {
            sb.Clear();
            sb.AppendLine("changed");
        }

// processStringBuilder(x);

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
247 words
Last Post: Is User Experience Important - A Case Study with Mspaint
Next Post: FillInteger Implementation in Delphi/Object Pascal

The Permanent URL is: Passing String or StringBuilder to Function in C# (By Value or By Reference)

4 Comments

  1. otebos

Leave a Reply