Difference between passing a reference type and a value type as argument to a method

后端 未结 3 1750
孤城傲影
孤城傲影 2021-01-29 07:34

Just got this confusion running in my mind throughout the day. I am very much confused between reference and value type being passed to a method.

Say I have 2 classes

3条回答
  •  野性不改
    2021-01-29 07:51

    Beside Reference Type and Value Type, there are Mutable Type and Immutable Type.

    Immutable means that object cannot and will not be changed after initialization. As a result, your statement only produces new string but does not modify original string.

    s += "Hi";

    The hello string object remains hello. Change is that s is assigned with a new object helloHi.


    You are unfortunate enough using string as an example.

    Try to use mutable types like StringBuilder in your example.

    public class C
    {
        public static void Main(string[] args)
        {
            StringBuilder s = new StringBuilder("hello");
            StringBuilder w = Changestring(s);
            StringBuilder x = s;
        }
    
        private static StringBuilder Changestring(StringBuilder s)
        {
            s.Append("Hi");
            return s;
        }
    }
    

提交回复
热议问题