1. Computing
Send to a Friend via Email

C# Programming Tutorial - About Strings and Chars


1 of 10

Strings 101
This C# programming tutorial is about String handling in C# 2.0 and higher. A String (note- uppercase S!) is a fundamental type, managed by the .NET framework. A string (lowercase s) is an alias in C# for the .NET String type. As I understand it, you can use either interchangeably though selecting string and pressing the F1 key will give different help pages.

Unlike C and C++, the underlying character type in a string is a 16 bit Unicode char. Mixing 16 bit chars with 8 bit chars from unmanaged code can be done but if you're used to 8 bit chars, there is a subtle difference and you need to call conversion routines.

The other thing about a C# string is that it is immutable which means read-only. Once you have assigned it, you can't change the original string value. If you try to alter it in some way, perhaps by appending another string it creates a new string. This can be very inefficient if done a lot but there is a StringBuilder class that will overcome that. More on that later in this tutorial.

Assigning A String

C# lets you assign a string as you'd expect -
 public string MyString= "A String";
A string is a reference type and the text is stored somewhere in memory where we don't have to concern ourselves with it.

Examples of Assigning String Literals

These are valid string values.
 "c:\\fred\\file.txt" - The \\ is treated as a single \. (See Strings and Characters on the next page)
 @"c:\fred\file.txt" - This is @quoted and the backslah \ is not processed. Microsoft call this a verbatim string. The backslashes are treated as characters not escape codes.
Use " (double quotes) instead of ' inside a verbatim string. If you are using text not containing any backslashes then the regular strings (without the @) are probably best. Use verbatim strings for file paths.

On the next page Strings and Chars

  1. About.com
  2. Computing
  3. C / C++ / C#
  4. C# / C Sharp
  5. Learn C Sharp
  6. C# Programming Tutorial - About Strings and Chars

©2014 About.com. All rights reserved.