Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Char.ToString() Method in C#
The Char.ToString() method in C# is used to convert a character to its equivalent string representation. This method is particularly useful when you need to convert a single character into a string for string operations or concatenation.
Syntax
Following is the syntax for the Char.ToString() method −
public override string ToString();
Return Value
The method returns a string object containing the character value converted to its string representation.
Using Char.ToString() Method
Example 1 - Converting Lowercase Character
Let us see an example to convert a lowercase character to its string representation −
using System;
public class Demo {
public static void Main() {
char ch = 'p';
Console.WriteLine("Value = " + ch);
char res1 = Char.ToLowerInvariant(ch);
Console.WriteLine("Lowercase Equivalent = " + res1);
string res2 = ch.ToString();
Console.WriteLine("String Equivalent = " + res2);
}
}
The output of the above code is −
Value = p Lowercase Equivalent = p String Equivalent = p
Example 2 - Converting Uppercase Character
Let us see another example with an uppercase character −
using System;
public class Demo {
public static void Main() {
char ch = 'D';
Console.WriteLine("Value = " + ch);
char res1 = Char.ToLowerInvariant(ch);
Console.WriteLine("Lowercase Equivalent = " + res1);
string res2 = ch.ToString();
Console.WriteLine("String Equivalent = " + res2);
}
}
The output of the above code is −
Value = D Lowercase Equivalent = d String Equivalent = D
Example 3 - Using ToString() with Numeric and Special Characters
using System;
public class Demo {
public static void Main() {
char[] characters = {'5', '@', 'Z', ' '};
foreach (char ch in characters) {
string converted = ch.ToString();
Console.WriteLine("Character: '{0}' -> String: "{1}" (Length: {2})",
ch, converted, converted.Length);
}
}
}
The output of the above code is −
Character: '5' -> String: "5" (Length: 1) Character: '@' -> String: "@" (Length: 1) Character: 'Z' -> String: "Z" (Length: 1) Character: ' ' -> String: " " (Length: 1)
Common Use Cases
String Concatenation: When you need to append a character to a string.
Type Conversion: Converting char data type to string for methods that require string parameters.
Array Processing: Converting character arrays to string arrays.
Display Formatting: Preparing character data for output or logging purposes.
Conclusion
The Char.ToString() method provides a simple way to convert any character to its string representation. This method is essential for type conversion operations and string manipulation tasks where individual characters need to be treated as strings.
