Archive for the ‘String’ Category

IntereString: String Vs string, == or .Equals, @, Stringbuilder

November 19, 2009

A lot of my C# development time involves working with and manipulating strings (a task common to most programmers). Here are some short answers to a few issues/questions I came accross:

String vs string
Lower case string is simply an alias for System.String in the .NET Framework.

== or .Equals
A rule of thumb is that for almost all reference types e.g. objects, use Equals when you want to test equality. == compares whether two references (i.e. object instances) refer to the same object.
Primitive types can be compared for equality using ==, but in the case of strings, the variables on each side of the operators must be of type string.
Have a look at the following code and output, taken from Jon Skeet’s blog.

using System;

public class Test
	static void Main()
        // Create two equal but distinct strings
        string a = new string(new char[] {'h', 'e', 'l', 'l', 'o'});
        string b = new string(new char[] {'h', 'e', 'l', 'l', 'o'});
        Console.WriteLine (a==b);
        Console.WriteLine (a.Equals(b));
        // Now let's see what happens with the same tests but
        // with variables of type object
        object c = a;
        object d = b;
        Console.WriteLine (c==d);
        Console.WriteLine (c.Equals(d));
The results are: 


@ before a string
Using @ before a string means the escape sequences are not processed. This making it easier to write fully qualified path names for example.
@”c:\Docs\Source\a.txt” // rather than “c:\\Docs\\Source\\a.txt”

String objects are immutable, and so editing them, using Replace for example, results in a entirely new string being created, with new memory allocation. The original string is left intact in memory.
The StringBuilder class is designed for situations when one needs to work with a single string and make an arbitrary number of iterative changes to it. New memory allocation is not needed.

Hope this helps, cos it helped me!