String Basics Part I

Friday, July 22, 2005

I’ve used the snippet of code at the end of this article twice in the last week to clear up some misunderstandings about strings in .NET.

System.String is a reference type in .NET. Don’t let anyone mislead you into thinking otherwise. You’ll hear people saying strings “act like value types”, but this doesn’t mean the runtime makes a copy of the string during assignment operations, and it doesn’t make a copy of a string when passing the string as a parameter.

The equality operator and String.Equals method compare the values of two string objects, and you won’t find a property or method on System.String with the ability to modify the contents of a string – only return a new string object. Because of these two behaviors we sometimes say strings have value type semantics (they feel like value types), but strings are reference types in the runtime. An assignment operation does not copy a string, but assigns a reference. The value given to a string parameter in a method call is the reference, not a copy of the string’s value.

using System;

class Class1

{

[STAThread]

static void Main(string[] args)

{

string s1 = "Hello";

string s2 = s1;

// this test will compare the values of the strings

// result will be TRUE since both s1 and s2

// refer to a string with the value "Hello"

bool result = String.Equals(s1, s2);

Console.WriteLine("String.Equals(s1, s2) = {0}", result);

// next we will check identity

// ReferenceEquals will return true if both parameters

// point to the same object

// result will be TRUE -both s1 and s2reference

// the same object.

// strings are reference types

// there is no copy made on assignment (s2 = s1)

result = Object.ReferenceEquals(s1, s2);

Console.WriteLine("Object.ReferenceEquals(s1, s2) = {0}", result);

// now we will make a copy of the string

s2 = String.Copy(s1);

// compare string values again

// result will be TRUE - both s1 and s2

// refer tostrings with the value of "Hello"

result = String.Equals(s1, s2);

Console.WriteLine("String.Equals(s1, s2) = {0}", result);

// check identity again

// result will be FALSE

// s1 and s2 point to different object instancesbecause we forced a copy

result = Object.ReferenceEquals(s1, s2);

Console.WriteLine("Object.ReferenceEquals(s1, s2) = {0}", result);

}

}


Comments
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!