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

前端 未结 2 753
渐次进展
渐次进展 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 ListInput = new List();
    
            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 input)
        {
    
            input = new List();
        }
    
        static void ChangeMyObject(ref List input)
        {
    
            input = new List();
        }
    
    
    }
    

    The output of this program is this:

    Input
    Input
    3
    3
    Output
    0
    

提交回复
热议问题