Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String object is really by reference? [duplicate]

I have being studying (newbie) .NET and I got some doubts.

Reading from a book examples I learnt that String are object then Reference Type.

So, I did this test and the result was different what I expected:

I'm really curious, is this an exception because "string" are special types?

class Program
{
    static void Main(string[] args)
    {
        SByte a = 0;
        Byte b = 0;
        Int16 c = 0;
        Int32 d = 0;
        Int64 e = 0;
        string s = "";
        Exception ex = new Exception();

        object[] types = { a, b, c, d, e, s, ex };

        // C#
        foreach (object o in types)
        {
            string type;
            if (o.GetType().IsValueType)
                type = "Value type";
            else
                type = "Reference Type";
            Console.WriteLine("{0}: {1}", o.GetType(), type);
        }

        // Test if change
        string str = "I'll never will change!";

        Program.changeMe(str);

        Console.WriteLine(str);
    }

    public static string changeMe(string param)
    {
        param = "I have changed you!!!";

        return ""; // no return for test
    }
}

Output:

System.SByte: Value type
System.Byte: Value type
System.Int16: Value type
System.Int32: Value type
System.Int64: Value type
System.String: Reference Type
System.Exception: Reference Type
I'll never will change!
like image 917
Ismael Avatar asked Oct 20 '09 23:10

Ismael


1 Answers

String is indeed a reference type. However, when your Main method calls changeMe(str), .NET passes a copy of the reference to str to changeMe in the param argument. changeMe then modifies this copy to refer to "I have changed you!!!", but the original str reference still points to "I will never change".

Being a reference type means that if you changed the state of the passed string, the caller would see those changes. (You can't do this to a string because strings are immutable, but you can do it to other reference types e.g. Control.) But reassigning a parameter doesn't change the value the caller passed in that parameter, even if that value is a reference.

like image 190
itowlson Avatar answered Oct 04 '22 02:10

itowlson