Dotnetfreaks' Blog | Dotnetfreaks' Blog - The string or System.String Type

Dotnetfreaks' Blog

Fabulous Adventures In DotNet

About the author

Author Name is someone.
E-mail me Send mail

Recent posts

Recent comments

Archive

Tags

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2012

The string or System.String Type


A String represents an immutable ordered set of characters. The String type is derived from Object, making it a reference type, and therefore, String objects (its array of characters) always live in the heap, never on a thread's stack. The String  type also implements several interface (IComparable/ IComparable<String>, ICloneable, IConvertible, IEnumerable/ IEnumerable<Char>, and IEquatable<String>). The String class is sealed no inheritance allowed and string is an alias for System.String in the .NET Framework.

Once created, a string can never get longer, get shorter, or have any of its characters changed. It allows you  to perform operations on a string without actually changing the string. If you perform a lot of string manipulations, you end up creating a lot of String objects on the heap, which causes more frequent garbage collections, thus hurting your application's performance. To perform a lot of string manipulations efficiently, use the StringBuilder class.


You can concatenate several strings to form a single string by using the C# + (plus) operator: 

String  sObj=”Hi” + “  “ + “Gentleman”; 

In this example all strings are literal strings so C# compiler concatenates them at compile time and end up just one string “Hi Gentleman” in the module's metadata. Using the + (plus)  operator on nonliteral strings causes the concatenation to be performed at run time. To concatenate several strings together at run time, avoid using the + operator as it creates multiple string objects on the garbage-collected heap. Instead, use the System.Text.StringBuilder type.


Verbatim Strings (“@”)

C# also offers a special way to declare a string in which all characters between quotes are considered part of the string. These special declarations are called verbatim strings and are typically used when specifying the path of a file or directory or when working with regular expressions. 

// Specifying the pathname of an application 
String file = "C:\\Windows\\System32\\pbrush.exe"; 

// Specifying the pathname of an application by using a verbatim string 
String file = @"C:\Windows\System32\pbrush.exe";

The @ symbol before the string tells the compiler that the string is a verbatim string. In effect, this  tells the compiler to treat backslash characters as backslash characters instead of escape characters.




Posted by Ajander Singh on Monday, October 06, 2008 11:17 AM
Permalink | Comments (0) | Post RSSRSS comment feed
Comments are closed