C# Convert ToChar(String)

Description

Convert ToChar(String) converts the first character of a specified string to a Unicode character.

Syntax

Convert.ToChar(String) has the following syntax.


public static char ToChar(
  string value
)

Parameters

Convert.ToChar(String) has the following parameters.

  • value - A string of length 1.

Returns

Convert.ToChar(String) method returns A Unicode character that is equivalent to the first and only character in value.

Example

The following example converts each element in a string array to a Char value.


//from  w ww .j  a  va2  s .c o m
using System;
public class MainClass{
  public static void Main(String[] argv){  
    string nullString = null;
    string[] strings = { "A", "This",  '\u0007'.ToString(), nullString };
    char result;
    foreach (string strng in strings)
    {
       try {
          result = Convert.ToChar(strng);
          Console.WriteLine("'{0}' converts to '{1}'.", strng, result);
       }   
       catch (FormatException)
       {
          Console.WriteLine("'{0}' is not in the correct format for conversion to a Char.",
                            strng);
       }
       catch (ArgumentNullException) {
          Console.WriteLine("A null string cannot be converted to a Char.");
       }   
    }

  }
}
    

The code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version