C# String

In C#, content regards with string includes:

1. String type

Its features:

  a. built-in reference type.

  b. immutable (meaning that a string can’t be modified once created) and sealed (meaning that it can’t be derived from).

  c. string equality performs value equality. If you want to check the refence equality, you need to cast the string object to be object and then do "==". See below:

  (object) str1 == (object) str2;

MODIFYING STRINGS
Strictly speaking, you never really modify a string. A string is immutable, meaning that it can’t change. What really happens when calling a method such as Insert, Remove,
or Replace is that the CLR creates a new string object and returns a reference to that new string object. The original string never changed.
This is a common mistake by people just getting started with C# programming, so remember this any time you look at a string after one of these operations, thinking that
it should be changed. Instead, assign the results of the operation to a new string variable. Assigning the result of the string manipulation to the same variable will work, too; it just assigns the new string object reference to the same variable.

THE INTERN POOL
The intern pool is a system table that eliminates duplication by allowing multiple references to the same constant string when the strings are identical. This saves system
memory. The intern-related methods of the string class enable a program to determine whether a string is interned and to place it in the intern pool to take advantage of the
associate memory optimizations.

In normal .NET development, it is not usual to work with the intern pool via Intern and IsInterned methods. If you do need to optimize your application to close detail, these
methods could prove useful. Any time you try to interact with methods that affect the normal operation of the CLR, you might want to consider using benchmarking and profiling
tools to ensure your efforts don’t accidentally have an opposite effect or cause other problems.

2. StringBuilder

With StringBuilder overhead occurs when instantiating the StringBuilder object, but with the string type, overhead occurs on every modification of a string because it
creates a new string object in memory. A rule of thumb to know when to use a StringBuilder rather than a string is to start using StringBuilder after four manipulations
of a string.

3. Regular expressions.

posted @ 2010-02-22 12:03  能巴  阅读(229)  评论(0编辑  收藏  举报