Shadman Kudchikar

C# String

C# String Manipulation, String Constructors, String Assignment, And The StringBuilder Class

Why is string manipulation so important? Because, as programmers, we do so much of it. In fact, on some days, it seems that everything is string manipulation. If you know how to program with strings, you’re a great way along the journey to becoming a powerful programmer. Fortunately, C# provides facilities for working with and manipulating strings. In this tutorial we will learn the types and methods related to strings, so that you can make short work of most common string-manipulation tasks in your projects.

Contents

This tutorial provides the information you need about:

Understanding C# Strings

In C#, a text string is stored in a data type named string, which is an alias to the System.String type. In other words, when you create a string, you instantiate a System.String object. In addition to its instance members, the System.String class has quite a few important static methods. These methods don’t require a string instance to work. It’s important to understand that the string type is immutable. This means that once it has been created, a string cannot be changed. No characters can be added or removed from it, nor can its length be changed. In those situations in which it appears that a string’s contents have been changed, what has really happened is that a new string instance has been created.

But wait, you say, my strings change all the time when I do things like:

using System;

class Program
{
    static void Main(string[] args)
    {
        string str = "I am having a";
        str += " great deal of fun.";
        str += " The End";
        Console.WriteLine(str);
        Console.ReadLine();
    }
}

/*
This example produces the following results:
I am having a great deal of fun. The End
*/

Well, my friend, what this set of statements actually does is create a new instance of the variable str each time a value is assigned to str. In other words, in this example, an instance of str has been created and a literal string value assigned to it three times.The statement that the type is immutable means that an instance cannotbe edited but it can be assigned.

Using an instance method without an assignment is syntactically legal, but it doesn’t do anything (has no effect). As a demonstration of my claim that an instance cannot be edited, examine the following code:

using System;

class Program
{
    static void Main(string[] args)
    {
        string str = "Mouser";
        str.Replace("u", "U");
        Console.WriteLine(str);
        Console.ReadLine();
    }
}

//Displays Mouser

The above code does not change the contents of the variable str, because an instance cannot be edited. Run the above code in your IDE, and you’ll see this result:

However, combining it with an assignment would work:

using System;

class Program
{
    static void Main(string[] args)
    {
        string str = "Mouser";
        str = str.Replace("u", "U");
        Console.WriteLine(str);
        Console.ReadLine();
    }
}

//Displays MoUser

The value of the newly assigned str instance is, of course, MoUser. If you carefully compare the two source code listings above, you’ll see that the only difference occurs in the two highlighted lines.

The second source code listing differs only by prefacing that line of code with str =, which tells the compiler to assign whatever follows the equal sign to the str instance of the String type.

In C# a type is defined by a class. There is, indeed, a String class. So, when I write string str = "Mouser";, what I’ve really done is created an instance of the String class called str, then assigned the text Mouser to it.

Is there any real problem with this use of assignment in conjunction with strings? Well, no, it’s easy enough to use assignments when you need to change the value of a string variable.

But,

Instantiating and destroying strings every time you need to change or edit one has negative performance consequences. If performance is an issue, you should consider working with instances of the System.Text.StringBuilder class, which are mutable (can be changed). The StringBuilder class is discussed later in this tutorial in a little more detail.

Once created, a string has a specific length which, of course, is fixed (since the string type is immutable). Unlike in the C language, in which a string is simply an array of characters terminated with a zero byte, a C# string is not a terminated array of characters. So, how does one determine the length of a C# string? As you probably know, you can query the read-only Length property of the string instance to find its length. Let’s write a short console program demonstrating the use of this property:

using System;

class Program
{
    static void Main(string[] args)
    {
        string name = string.Empty;
        do
        {
            Console.Write("Please enter a name (enter 'quit' to exit): ");
            name = Console.ReadLine();
            if (name.Trim().ToLower() != "quit")
            {
                Console.WriteLine("{0}, is {1} characters in length.", 
                	name, name.Length);
            }
        } while (name.Trim().ToLower() != "quit");
    }
}

/*
This example produces the following results:
Please enter a name (enter 'quit' to exit): Shadman
Shadman, is 7 characters in length.
Please enter a name (enter 'quit' to exit): quit
*/

C# Char type

Char is a value type that contains a single Unicode character. While chars have a numeric value from hexadecimal 0×0000 through 0xFFFF, they are not directly numerically usable without explicit type casting.

Literal values are assigned to char variables using single quotes. The literal can be a simple, single letter, or an escape sequence (for more on escape sequences, see the next section).Here are two examples:

char chr = 'P'; // contains capital P
char pi = '\u03A0'; // contains capital Pi 

The char data type is related to the string data type: A string can be constructed from (or converted into) an array of characters but string and char are two distinct types.

Suppose you have a string defined like this:

string str = "rotfl";

You can retrieve a character of the string using the string’s indexer. For example, the following statement

char chr = str[1];

stores the character ‘o’ in the variable chr. But you cannot set a character in the string with a statement like str[1] = 'a'; because the indexer property of the String class is read-only.(Actually, one would expect this in any case, because the string instance is immutable.)

If you use the Object Browser to have a look at the String class, you’ll see that its indexer property, declared as this[int], has a get accessor, but no set accessor.

C# Control Characters

The backslash ‘\’ is a special control character, also called the escape character.The character after the backslash has a special significance. See the following table for the meaning of each escape sequence:

CHARACTER MEANING
\b Backspace
\t Tab
\r Carriage return
\n New line
\v Vertical tab
\f Form feed
\u, \x A single Unicode character when followed by a four-digit hexadecimal number
\” Double quote
\’ Single quote
\\ Backslash

Here is a very brief program that demonstrates use of the backspace escape character:

using System;

class Program
{
    static void Main(string[] args)
    {
        Console.Write("This is line #1\b\b");
        Console.Write("number 2");
        Console.ReadLine();
    }
}

//Displays This is line number 2

As you can see, there are two backspace escape characters at the end of the first Console.Write() parameter. I’ve highlighted these in the source code listing above. These have the effect of backing the cursor up to just in front of the # symbol. The subsequent Console.Write() invocation then prints “number 2”, starting at the position occupied by the # symbol, and thus effectively overwriting #1.

The escape sequences u or x are used(interchangeably) to specify a single Unicode character. For example, x03A9 and u03A9 both mean the Greek letter capital omega. The escape sequences x03A3 and u03A3 will appear as the Greek letter capital sigma:

using System;

class Program
{
    static void Main(string[] args)
    {
        Console.Write("This is Omega: {0}. And this is Sigma: {1} ",
'\u03A9', '\u03A3');

        Console.ReadLine();
    }
}

/* 
This example produces the following results:
This is Omega: Ω. And this is Sigma: Σ
*/

A complete listing of unicode character sets can be found at http://www.unicode.org/charts/.

C# String Assignment

There are different ways to create strings in C#. You can, for instance, declare a string variable, without initializing it, such as in this example:

string mystring;

While this is legal, we’ve also discussed the fact that attempting to use an uninitialized string variable causes a compiler error. For this reason, it’s generally a good idea to initialize a string variable when you declare it:

string mystring = "Hello, world!";

Because a string variable is a reference type, it can be initialized to null:

string mystring = null;

And initializing a string to null is not the same thing as initializing it to an empty string. The above is not equivalent to this:

string mystring = string.Empty;

In the case of the null assignment, no memory has been allocated for the string. An attempt to determine the length of a null string by using its Length property causes an exception to be thrown. For an example of this, see the following program listing, and then the output it produces. The program will compile okay, because there is no syntax error. However, attempting to execute the highlighted line causes a runtime error:

using System;

class Program
{
    static void Main(string[] args)
    {
        string mystring = null;
        Console.WriteLine("Length of mystring is {0}", mystring.Length);
        Console.ReadLine();

    }
}

The Length property of an empty string is 0. The preferred way to initialize an empty string is to use the static Empty field of the String class: string str = string.Empty;

However, you will sometimes see it done thusly: string str = "";

C# String Constructor

The String class itself has eight constructors. If you look in the Object Browser, you can see that five of these use pointers and are not safe under the rules of the Common Language Specification (CLS) that.NET languages must follow. We will only discuss the other three constructors.

When a method has more than one form, via differing method signatures, it is said to be overloaded. You may also know that a constructor is a special class method that, if present, is invoked whenever a new instance of that class is created. Well, the String class has several overloaded constructors.

The first such overloaded constructor that we’ll discuss takes two parameters — a character and an integer. It then produces a string of that particular character that is x characters in length, where x is the value of the integer passed as the constructor’s second argument. This constructor takes the following form:

String(char, int)

For example, the following lines of code, placed inside the Main method of a Console C# application…

using System;

class Program
{
    static void Main(string[] args)
    {
        string s = new string('a', 5);
        Console.WriteLine(s);
        Console.ReadLine();
    }
}

//Displays aaaaa

The next overloaded string constructor we’ll consider takes the following form:

String(char[])

This constructor takes a character array as a parameter, and converts the character array into a string. For example,the following code…

using System;

class Program
{
    static void Main(string[] args)
    {
        char[] mychararray = new char[5] { 'H', 'e', 'l', 'l', 'o' };
        string mystring = new string(mychararray);
        Console.WriteLine(mystring);
        Console.ReadLine();
    }
}

//Displays Hello

The final overloaded string constructor we’llconsider is simply an extension of the constructor we just examined,and takes this form:

String(char[] value, int startIndex, int length);

Like the previous constructor, it converts a character array into a string, but it additionally will then derive a string with a particular starting position upto the length specified within the converted string. For example, if these lines were put into a console program…

using System;

class Program
{
    static void Main(string[] args)
    {
        char[] mychararray = 
        	new char[11] { 'N', 'e', 'w', 'Y', 'o', 'r', 'k' };
        string mystring = new string(mychararray, 3, 4);
        Console.WriteLine(mystring);
        Console.ReadLine();
    }
}

…the output would be York.

C# Verbatim Strings

You could use the @symbol to use a keyword as an identifier if you were so inclined. You could create variables named, for example, @if, @string, and @true; but, just because one can do something, doesn’t mean it is a good idea.

In the context of strings, the @ symbol isused to create verbatim string literals. The @ symbol tells the string constructor to use the string literal that follows it literally even if it includes escape characters or spans multiple lines.

This comes in handy when working with directory paths (without the @, you would have to double each backslash). For example, the following two strings are equivalent:

string desktop = "C:\\Users\\pc\\Documents\\VS"; //uses 8 slashes
string desktop = @"C:\Users\pc\Documents\VS"; //uses 4 slashes

C# Multiline String

You can also use the ampersand symbol to causea single string to span more than one line. For example, consider the following program listing, and the output it produces:

using System;

class Program
{
    static void Main(string[] args)
    {
        string str =
@"I'm so happy to be a string
that is split across
a number of different
lines.";

        Console.WriteLine(str);
        Console.ReadLine();
    }
}

In console mode, line breaks are preserved. In a WinForms application (we’ll learn how to code those in later tutorials), you could assign str to a textbox control that has its multiline property set to true, and all line breaks and whitespace would be faithfully preserved.

C# String Methods

The String class provides many powerful instance and static methods. These methods are described in this section. Most of these methods are overloaded, so there are multiple ways that each can be used. The table below describes many of the instance methods of the String class.

METHOD WHAT IT DOES
Clone Returns a reference to the instance of the string.
CompareTo Compares this string with another.
CopyTo Copies the specified number of characters from the string instance to a char array.
EndsWith Returns true if the specified string matches the end of the instance string.
Equals Determines whether the instance string and a specified string have the same value.
GetEnumerator Method required to support the IEnumerator interface.
IndexOf Reports the index of the first occurrence of a specified character or string within the instance.
Insert Returns a new string with the specified string inserted at the specified position in the current string.
LastIndexOf Reports the index of the last occurrence of a specified character or string within the instance.
PadLeft Returns a new string with the characters in this instance right-aligned by padding on the left with spaces or a specified character for a specified total length.
PadRight Returns a new string with the characters in this instance left-aligned by padding on the right with spaces or a specified character for a specified total length.
Remove Returns a new string that deletes a specified number of characters from the current instance beginning at a specified position.
Replace Returns a new string that replaces all occurrences of a specified character or string in the current instance, with another character or string.
Split Identifies the substrings in this instance that are delimited by one or more characters specified in an array, then places the substrings into a string array.
StartsWith Returns true if the specified string matches the beginning of the instance string.
Substring Returns a substring from the instance.
ToCharArray Copies the characters in the instance to a character array.
ToLower Returns a copy of the instance in lowercase.
ToUpper Returns a copy of the instance in uppercase.
Trim Returns a copy of the instance with all occurrences of a set of specified characters from the beginning and end removed.
TrimEnd Returns a copy of the instance with all occurrences of a set of specified characters at the end removed.
TrimStart Returns a copy of the instance with all occurrences of a set of specified characters from the beginning removed.

Whereas the above table shows many of the String class instance methods, the following tables shows some of the static methods of the String class.

METHOD WHAT IT DOES
Compare Compares two string objects.
CompareOrdinal Compares two string objects without considering the local national language or culture.
Concat Creates a new string by concatenating one or more strings.
Copy Creates a new instance of a string by copying an existing instance.
Format Formats a string using a format specification. See Formatting Overview in online help for more information about format specifications.
Join Concatenates a specified string between each element in a string to yield a single concatenated string.

C# String Clone

Here is a program that demonstrates the use of String.Clone().What this program shows is that cloning a string returns a reference to that string instance, which can be assigned to another string variable,giving that other string variable a reference to the exact same location in memory. In other words, both strings will reference the same instance, after cloning has occurred.

using System;

class Program
{

    static void Main()
    {

        bool test = false;
  
        string s1 = "Shadman";
        string s2 = "Sharif";
        string s3 = "Kudchikar";
  
        Console.WriteLine("s1 = {0}, s2 = {1}, s3 = {2}", s1, s2, s3);
  
        s2 = (string)s1.Clone(); 
        Console.WriteLine("s2 = (string)s1.Clone(); ");        
  
        test = SameValue(s1, s2);
  
        if (test)
        {
           Console.WriteLine("s2 holds the same value that s1 holds, {0}", s1);
        }
  
        test = ReferencesSameObject(s1, s2);
  
        if (test)
        {
           Console.WriteLine("s1 and s2 reference the same instance object.");
        }
  
        s2 = s3;
  
        Console.WriteLine("s2 = s3; s2 = {0} and s3 = {1}", s2, s3);
  
        test = SameValue(s2, s3);
  
        if (test)
        {
           Console.WriteLine("s2 and s3 hold the same value.");
        }
  
        test = ReferencesSameObject(s2, s3);
  
        if (test)
        {
           Console.WriteLine("s2 and s3 reference the very same instance.");
        }
        else
        {
           Console.WriteLine("s2 and s3 do NOT reference the same instance.");
        }
  
        Console.ReadLine();

    }//end Main

    private static bool SameValue(object o1, object o2)
    {
        if (o1.Equals(o2))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    private static bool ReferencesSameObject(object o1, object o2)
    {

        if (Object.ReferenceEquals(o1, o2))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

/*
This example produces the following results:
s1 = Shadman, s2 = Sharif, s3 = Kudchikar
s2 = (string)s1.Clone();
s2 holds the same value that s1 holds, Shadman
s1 and s2 reference the same instance object.
s2 = s3; s2 = Kudchikar and s3 = Kudchikar
s2 and s3 hold the same value.
s2 and s3 reference the very same instance.
*/

C# String Copy

Whereas the Clone() method of the String object returns a reference to the string instance, the static Copy() method creates a new instance of a string by copying an existing instance, as the following program demonstrates:

using System;

class Program
{
    static void Main(string[] args)
    {
        string str1 = "abc";
        string str2 = "xyz";
        Console.WriteLine("1) str1 = '{0}'", str1);
        Console.WriteLine("2) str2 = '{0}'", str2);
        Console.WriteLine("Copy…");
        str2 = String.Copy(str1);
        Console.WriteLine("3) str1 = '{0}'", str1);
        Console.WriteLine("4) str2 = '{0}'", str2);
        Console.ReadLine();
    }
}

/*
This example produces the following results:
1) str1 = 'abc'
2) str2 = 'xyz'
Copy…
3) str1 = 'abc'
4) str2 = 'abc'
*/

C# String IndexOf

Moving on, we come to the String.IndexOf() method, which reports the index of the first occurrence of a specified character or string within the instance. Remembering that the first position in a string is position 0, what value do you think i holds below?

string s = "abcde";
int i = s.IndexOf("b");

If you said “i = 1”, you are correct! How about character e? Position 4, right!

It is worth noting that this method can be useful whenever you want to determine if a string contains a particular character or substring. The integer value returned by this method, if the specified character or string is not found, is negative one, i.e., -1. This can come in handy in any number of common programming tasks.

C# String Split

The String.Split method is useful for breaking up multiple strings in a value. When developing programs that interoperate with external systems, it’s often necessary to process data in a common format. For example, a program may wish to process data from an Excel spreadsheet. Excel has the capability to export a worksheet in Comma Separated Value (CSV) format. Using the C# string Split() method you can extract the values from in between the commas.

using System;

class Program
{
   static void Main(string[] args)
   {
        // comma delimited string
        string commaDelimited = "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec";

       Console.WriteLine("Original Comma Delimited String: \n{0}\n", commaDelimited);

       // separate individual items between commas
        string[] year = commaDelimited.Split(new char[] {','});

       Console.WriteLine("Each individual item: ");

       foreach(string month in year)
       {
            Console.Write("{0} ", month);
       }
       Console.WriteLine("\n");

       Console.ReadLine();
       
   }
}

/*
This example produces the following results:
Original Comma Delimited String:
Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec

Each individual item:
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
*/

C# String Join

Similar to string.Split method, elements of an array may be combined into a delimited string by using the Join() method. The simplest overload of the Join() method accepts two parameters: a string, which separates each array element, and the array of elements to be combined. The Join() method is static, requiring the String type identifier, rather than a string instance, to implement the command. The following line from the listing creates a string with all year elements in a sequence and separated by colons:

using System;

class Program
{
   static void Main(string[] args)
   {
        // comma delimited string
        string commaDelimited = "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec";

       Console.WriteLine("Original Comma Delimited String: \n{0}\n", commaDelimited);

       // separate individual items between commas
        string[] year = commaDelimited.Split(new char[] {','});

       // combine array elements with a new separator
        string colonDelimeted = String.Join(":", year);

       Console.WriteLine("New Colon Delimited String: \n{0}\n", colonDelimeted);
       Console.ReadLine();
       
   }
}

/*
This example produces the following results:
Original Comma Delimited String:
Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec

New Colon Delimited String:
Jan:Feb:Mar:Apr:May:Jun:Jul:Aug:Sep:Oct:Nov:Dec
*/

C# String Trim

In C#, the string Trim method is used to remove all trailing and leading whitespace characters from the specified string object. By using Trim() method, we can also remove all occurrences of specified characters from the start and end of the current string.

using System;

class Program
{
    static void Main(string[] args)
    {
        // Trim Whitespaces
        string str1 = "  Shadman ";
        string str2 = "    Sharif    ";
        string str3 = "    Kudchikar";
        Console.WriteLine("Before Trim: {0} {1} {2}", str1, str2, str3);
        Console.WriteLine("After Trim: {0} {1} {2}", str1.Trim(), str2.Trim(), str3.Trim());
        char[] trimChars = { '*', '@', ' ' };
        // Trim with Characters
        string str4 = "@@**  John Doe  **@";
        Console.WriteLine("Before Trim: {0}", str4);
        Console.WriteLine("After Trim: {0}", str4.Trim(trimChars));            
        Console.ReadLine();

    }
}

/*
This example produces the following results:
Before Trim:   Shadman      Sharif         Kudchikar
After Trim: Shadman Sharif Kudchikar
Before Trim: @@**  John Doe  **@
After Trim: John Doe
*/

C# Substring

Another very handy instance method of the String object is String.Substring() instance method, which returns a substring (i.e., a string that lies within the string) from the instance string, by acting upon two integer values you pass the method as arguments for its parameters. The form that this method takes is String.Substring(start, length), where start is the position within the string where the substring starts, and length is the number of characters, beginning with the character found at position start, that the substring holds.

Perhaps an example will help. Let’s take the word internet. To extract the string net from it, we’d have something like this:

string s = "internet";
string t = s.Substring(5,3);

Regex.Replace

Another way to search a string is by using a regular expression, which uses a pattern-matching notation that can quickly parse large amounts of text looking for a specific format. Regular expressions can be useful when validating user input (such as an e-mail address, ZIP code, or date). Below code strips all titles from the names that you pass it. Imagine how much work it would have been to create this when using IndexOf and SubString.

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main(string[] args)
    {
        string pattern = "(Mr\\.? |Mrs\\.? |Miss |Ms\\.? )";
        string[] names = { "Mr. Henry Hunt", "Ms. Sara Samuels",
"Abraham Adams", "Ms. Nicole Norris" };
        foreach (string name in names)
        	Console.WriteLine(Regex.Replace(name, pattern, String.Empty));
        Console.ReadLine();
    }
}

/*
This example produces the following results:
Henry Hunt
Sara Samuels
Abraham Adams
Nicole Norris
*/

C# String Insert

The String.Insert() method returns a new string with a specified string of characters inserted into the instance string at the specified position. Forexample, let’s say we have a string holding a first name and a lastname, and we want to insert middlename, in quotation marks, in between the two:

using System;

class Program
{
    static void Main(string[] args)
    {
        string s = "Shadman Kudchikar";
        Console.WriteLine("Example #1:" + s);
        Console.WriteLine("after insertion…");
        string t = "Sharif ";
        s = s.Insert(8, t);
        Console.WriteLine(s);
        Console.WriteLine();
        Console.WriteLine("Example #2:");
        s = "abcefg";
        Console.WriteLine(s + " //missing letter d");
        Console.WriteLine("after insertion…");
        t = "d";
        s = s.Insert(3, t);
        Console.WriteLine(s);
        Console.ReadLine();
    }
}

/*
This example produces the following results:
Example #1:Shadman Kudchikar
after insertion.
Shadman Sharif Kudchikar

Example #2:
abcefg //missing letter d
after insertion.
abcdefg
*/

StringBuilder C#

As I mentioned earlier in this tutorial, instances of the StringBuilder class as opposed to the String class are mutable, or dynamically changeable. StringBuilder is located in the System.Text namespace. It does not have nearly as many members as the String class but it does have enough to get most jobs done. If you have a situation in which you need to perform many string operations for example, within a large loop from a performance view point it probably makes sense to use StringBuilder instances instead of String instances. In many ways the StringBuilder behaves like a String.

But,

For string-processing intensive applications, StringBuilder is the better choice because its mutability means not nearly so many instances need to be created.

A popular use of StringBuilder is to build up a long string by repeatedly calling Append. This approach is much more efficient than repeatedly concatenating ordinary string types:

using System;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 50; i++) sb.Append(i + ",");
        Console.WriteLine(sb.ToString());
        Console.ReadLine();
    }
}

/*
This example produces the following results:
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,
23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,
43,44,45,46,47,48,49,
*/

In our example, the expression i + “,” means that we’re still repeatedly concatenating strings. However, this incurs only a small performance cost in that the strings in question are small and don’t grow with each loop iteration. For maximum performance, however, we could change the loop body to this:

{ sb.Append (i); sb.Append (","); }

Also,

AppendLine performs an Append that adds a new line sequence (“\r\n” in Windows). AppendFormat accepts a composite format string, just like String.Format. As well as the Insert, Remove, and Replace methods (Replace works like string’s Replace), StringBuilder defines a Length property and a writable indexer for getting/setting individual characters.

C# String Format

When displaying strings to the user, you want to make sure that they are in the right format. Especially when working with culture-sensitive data such as DateTime or numbers, it’s important to make sure that the string is displayed in a manner that is suitable for current users and their settings.

Formatting is the process of converting an instance of a type to a string representation. When converting an instance to a string, the basic way of doing this is to call the ToString method that’s defined as a virtual member on System.Object. Overriding ToString is a good practice. If you don’t do this, ToString will return by default the name of your type. When you override ToString, you can give it a more meaningful value, as below code shows.

using System;

public class Person
{
    public Person(string firstName, string lastName)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
    }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public override string ToString()
    {
        return FirstName + " " + LastName;
    }
}

class Program
{
    static void Main(string[] args)
    {

        Person p = new Person("John", "Doe");
        Console.WriteLine(p); // Displays 'John Doe'
        Console.ReadLine();
    }
}

When an object has multiple string representations, overriding ToString is not enough. For example, a Temperature object can display its temperature in degrees Fahrenheit, Celsius, or Kelvin. An integer value can also be displayed in multiple ways. Maybe it represents a phone number or an amount of money.

To enable this kind of behavior, you can use format strings, which are strings that describe how an object should display. The .NET Framework uses them for numeric types, dates, times, and enumerations,

using System;

class Program
{
    static void Main(string[] args)
    {
        double cost = 1234.56;
        Console.WriteLine(cost.ToString("C",
        new System.Globalization.CultureInfo("en-US")));
        Console.ReadLine();
    }
}

// Displays $1,234.56

C# Datetime Format

You can use the same approach when displaying C# DateTime ToString. Depending on the culture, the formatted output can be completely different. Below code shows how to use different format strings with a DateTime for an English culture.

using System;
using System.Globalization;

class Program
{
    static void Main(string[] args)
    {
        DateTime d = new DateTime(2013, 4, 22);
        CultureInfo provider = new CultureInfo("en-US");
        Console.WriteLine(d.ToString("d", provider)); 
        Console.WriteLine(d.ToString("D", provider)); 
        Console.WriteLine(d.ToString("M", provider)); 
        Console.ReadLine();
    }
}

/*
This example produces the following results:
4/22/2013
Monday, April 22, 2013
April 22          
*/

Providing the correct CultureInfo is important when formatting values. It contains all the necessary information about how a particular type is displayed in that culture. In the same way, it’s important to make sure that when you save values to a database; for example, you do this in a culture-insensitive way. If the culture-insensitive data is than loaded, it can be formatted depending on the user who is viewing the data.

You can also implement this custom formatting on your own types. You do this by creating a ToString(string) method on your type. When doing this, make sure that you are compliant with the standard format strings in the .NET Framework.

For example, a format string of G should represent a common format for your object (the same as calling ToString()) and a null value for the format string should also display the common format.

Here is an example…

public class Person
{
    public Person(string firstName, string lastName)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
    }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public override string ToString()
    {
        return FirstName + " " + LastName;
    }

    public string ToString(string format)
    {
        if (string.IsNullOrWhiteSpace(format) || format == "G")
        {
            format = "FL";
        }

        format = format.Trim().ToUpperInvariant();
        switch (format)
        {
            case "FL":
                return FirstName + " " + LastName;
            case "LF":
                return LastName + " " + FirstName;
            case "FSL":
                return FirstName + ", " + LastName;
            case "LSF":
                return LastName + ", " + FirstName;
            default:
                throw new FormatException(String.Format(
                "The ‘{0}' format string is not supported.", format));
        }
    }
}

That’s all for now. Thanks for reading the post. Please let me know if there is any mistake or any modification needed in the comment below. Thanks in advance!

References


comments powered by Disqus