why to use ref keyword for passing string parameter in function calling

前端 未结 2 752
渐次进展
渐次进展 2021-01-27 17:59

String is a reference type , so why we have to attach ref keyword ahead of string variable when we are passing in a function call for getting change in a main function For ex:

相关标签:
2条回答
  • 2021-01-27 18:25

    Actually, this has nothing to do with the parameter being immutable, nor does it have to do with the parameter being a reference type.

    The reason you don't see a change is that you assign a new value to the parameter inside the function.

    Parameters without the ref or out keywords are Always passed by value.
    I know right now you are raising your eyebrows but let me explain:
    A reference type parameter that is passed without the ref keyword is actually passing it's reference by value.
    For more information read this article by Jon Skeet.

    To demonstrate my claim I've created a small program that you can copy and paste to see for your self, or simply check this fiddle.

    using System;
    using System.Collections.Generic;
    
    public class Program
    {
        public static void Main()
        {
            String StringInput = "Input";
    
            List<int> ListInput = new List<int>();
    
            ListInput.Add(1);
            ListInput.Add(2);
            ListInput.Add(3);
    
            Console.WriteLine(StringInput);
    
            ChangeMyObject(StringInput);
    
            Console.WriteLine(StringInput);
    
    
            Console.WriteLine(ListInput.Count.ToString());
    
            ChangeMyObject(ListInput);
    
            Console.WriteLine(ListInput.Count.ToString());
    
    
    
            ChangeMyObject(ref StringInput);
    
            Console.WriteLine(StringInput);
    
            ChangeMyObject(ref ListInput);
    
            Console.WriteLine(ListInput.Count.ToString());
    
    
    
        }
    
        static void ChangeMyObject(String input)
        {
    
            input = "Output";
        }
    
        static void ChangeMyObject(ref String input)
        {
    
            input = "Output";
        }
    
    
        static void ChangeMyObject(List<int> input)
        {
    
            input = new List<int>();
        }
    
        static void ChangeMyObject(ref List<int> input)
        {
    
            input = new List<int>();
        }
    
    
    }
    

    The output of this program is this:

    Input
    Input
    3
    3
    Output
    0
    
    0 讨论(0)
  • 2021-01-27 18:43

    Update passing by reference as per comments below.

    When you add the ref keyword in, you are passing by value passing a reference to the underlying value and can therefore, change the value of the data. A reference variable is like a pointer, not the value itself.

    Read the MSDN article.

    0 讨论(0)
提交回复
热议问题