Search code examples
c#stringtypesreferencevalue-type

Why String is Value type although it is a class not a struct?


Take the following example:

string me = "Ibraheem";
string copy = me;
me = "Empty";
Console.WriteLine(me);
Console.WriteLine(copy);

The output is:

Empty
Ibraheem

Since it is class type (i.e. not a struct), String copy should also contain Empty because the = operator in C# assigns reference of objects rather than the object itself (as in C++)??


Solution

  • System.String is not a value type. It exhibits some behaviors that are similar to value types, but the behavior you have come across is not one of them. Consider the following code.

    class Foo 
    { 
         public string SomeProperty { get; private set; }
         public Foo(string bar) { SomeProperty = bar } 
    }
    
    Foo someOtherFoo = new Foo("B");
    Foo foo = someOtherFoo;
    someOtherFoo = new Foo("C");
    

    If you checked the output of foo.SomeProperty, do you expect it to be the same as someOtherFoo.SomeProperty? If so, you have a flawed understanding of the language.

    In your example, you have assigned a string a value. That's it. It has nothing to do with value types, reference types, classes or structs. It's simple assignment, and it's true whether you're talking about strings, longs, or Foos. Your variables temporarily contained the same value (a reference to the string "Ibraheem"), but then you reassigned one of them. Those variables were not inextricably linked for all time, they just held something temporarily in common.