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

后端 未结 3 1703
孤城傲影
孤城傲影 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:59

    First to know, passing by value doesn't change initial variable value, where passing by reference also changes initial variable value referenced by method.

    By default int treated as value type, thus it is passed by value. However, a String even declared as a class (reference type), it is immutable by default with sealed modifier, thus treated as passing by value and adding new characters just create new instance of String, not changing current one.

    By adding ref keyword you can change int behavior to passing-by-reference:

    public Class B
    {
        public static void main(string[] args)
        {
            int s = 99;
            int w = Changeint(s); // w has changed
            int x = s; // s has also changed
        }       
    
        private int Changeint(ref int s)
        {
                s += 30; // result = 129
                return s;
        }
    }
    

    For class A, you need a StringBuilder instance to accomplish "helloHi":

    public Class A
    {
        public static void main(string[] args)
        {
            String s = “hello”;
            String w = Changestring(s);
            String x = w; // if you assign s to x, you will just get "hello"
        }
    
        private string Changestring(string s)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(s);
            sb.Append(“Hi”);
            return sb.ToString(); // "helloHi"
        }
    }   
    

    CMIIW.

提交回复
热议问题