Team LiB
Previous Section Next Section

Chapter 6: Strings

String Creation

Strings are a way to combine a group of characters for presentation to the user. In C#, we have the benefit of a built-in string class in .NET, but we can also use traditional C-style strings in arrays. The big advantage of using the .NET string is that it has built-in support for common methods that you may wish to use on a string, such as copy, concatenate, and so forth.

Another advantage of the .NET string class is that it produces nonmutable strings. This prevents a string from being overwritten because a pointer was being used to access the string, as sometimes occurred with C++ strings. If you truly desire to have a mutable string, you should use the StringBuilder class from the System.Text namespace, as demonstrated in several examples in this chapter.

C-style strings are nothing more than an array of chars that is null-terminated. Remember that an array is a block of contiguous memory of the same type and is a reference variable. To declare and define a C-style string, create a char array, as in this example:

char[] MyString = new char[6] {'H', 'e', 'l', 'l', 'o', '\0'};

This creates a string that looks very similar to the following in memory:

0

1

2

3

4

5

H

e

l

l

o

\0

Another and more preferred way to handle strings is to use the built-in string class, which provides a variety of methods that perform common tasks. To define and declare a new string class, use the string keyword, as in the following example:

string MyString = new string("Hello");

This creates a new string that is initialized with the word "Hello" that is automatically null-terminated (\0).

Note 

By default, strings are Unicode in C#. It is also important to remember that the C# string keyword is an alias for System.String.

The following example demonstrates creating strings.

Code Example: Creating Strings
Start example

using System;

namespace Client.Chapter_6___Strings
{
      class CreatingStrings
      {
            static void Main(string[] args)
            {
                  char MyChar = 'A';

                  MyChar = (char)65;
                 //Creates a Unicode array
                  char[] MyChar2 = {'H','e','l','l','o','\0'};

                  char[] MyChar3 = new char[5];
                  MyChar3[0] = 'H';
                  MyChar3[1] = 'e';
                  MyChar3[2] = 'l';
                  MyChar3[3] = 'l';
                  MyChar3[4] = 'o';
                  MyChar3[5] = '\0';
            }
      }
}

using System;

namespace MyNamespace
{
      class MyMainClass
      {
            static void Main(string[] args)
            {
                 //Creates a string
                  string MyString = "hello";
            }
      }
}
End example

Team LiB
Previous Section Next Section