1. Home
  2. Computing & Technology
  3. C / C++ / C#

C# Programming Tutorial - About Strings and Chars

By David Bolton, About.com

2 of 10

String and Char Conversions in C#

We've seen string assignment as in
string s1="A String"
but there are lots more ways to do it. C# is a bit more flexible because all types inherit a ToString() method. This means that you don't have to call functions like itoa to do type conversions to string. You can even do it with a numeric or character literal.
string s1='A'; // does not work
But this does explicitly:
string s2= 'A'.ToString();
string s3= 4.ToString();
and this, although a bit clumsy lets you pull a character out of a string.
string s4 = "Ooops"[3].ToString();
// p
This method is there because all variables are descended from type object which comes with a ToString() method. Example 1 demonstrates unicode as well.

Download example 1

If you use Unicode constants, remember that a Unicode char is of type string not char. That's why the unicode example 1 doesn't require a .ToString() whereas s2 = 'A'.ToString() does. You can see the type of any variable, object etc by suffixing it with

.GetType().ToString();
as is done for variable stu.
string stu = "\u0168".GetType().ToString();
The notation "\u0168" is how you declare Unicode literals. A Unicode char literal is treated as a string as some Unicode chars are themselves made up of multiple chars. If you aren't doing anything much with text processing then in most cases you can index into a string using length and the chars indexer. If though you are likely to encounter text from other locales then take a look at the StringInfo Class which makes it easy to split a string into multiple Unicode chars. Unicode is sufficiently complex to deserve its own tutorial so we'll move quickly on for now. We'll stick to normal chars (known as UTF-16) for the rest of this tutorial.

On the next page More on strings and chars

Explore C / C++ / C#
By Category
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C# / C Sharp
  5. Learn C Sharp
  6. Strings and Char Conversions in C#

©2009 About.com, a part of The New York Times Company.

All rights reserved.