17. C# (Char)
Source: Dev.to
The Real Goal of This Lesson
“When you only need a single character, why should you use
charinstead ofstring?”
This lesson is not about syntax. It is about:
- Representing data precisely
- Developing sensitivity to type modeling
- Choosing the smallest accurate abstraction
It is a modeling‑discipline step.
string vs char
string text = "A";
- A sequence of characters
- Uses double quotes
" - Internally represents multiple
charvalues - Can contain one, many, or zero characters – it is a collection
char letter = 'A';
- Exactly one character
- Uses single quotes
' - Represents a single Unicode value – it is atomic
| Type | Meaning | Quotes |
|---|---|---|
string | Collection of characters | " " |
char | Exactly one character | ' ' |
This distinction is structural, not merely stylistic.
Example: Grade conversion
static string ConvertPointsToGrade(int points)
{
return "A";
}
The return value is always a single symbol ("A", "B", "C").
A more precise representation uses char:
static char ConvertPointsToGrade(int points)
{
return 'A';
}
A grade is not a sentence, word, or multiple characters—it is a single symbolic value. char models that precisely.
static char GetGrade()
{
return "A"; // compile‑time error
}
Why? "A" is a string, but the method expects a char. The types differ, so the code fails at compile time.
Correct version:
static char GetGrade()
{
return 'A';
}
Full program example
using System;
class Program
{
static void Main()
{
Console.WriteLine("Enter your score:");
string input = Console.ReadLine();
int score = int.Parse(input);
char grade = ConvertToGrade(score);
Console.WriteLine($"Your grade is: {grade}");
Console.ReadKey();
}
static char ConvertToGrade(int score)
{
if (score >= 90) return 'A';
else if (score >= 80) return 'B';
else if (score >= 70) return 'C';
else if (score >= 60) return 'D';
else if (score >= 0) return 'F';
else return '!'; // invalid input indicator
}
}
Observe: The method returns a single character, not a string. Replacing return 'A'; with return "A"; causes a compile‑time error. Changing the method signature to static string ConvertToGrade(int score) would make the string return compile, but the type modeling would be less precise.
Accessing a char from a string
string name = "Sabin";
Console.WriteLine(name[0]); // prints 'S'
name[0] is a char.
Another example:
using System;
class Program
{
static void Main()
{
string word = "Hello";
char firstLetter = word[0];
Console.WriteLine(firstLetter);
Console.ReadKey();
}
}
Output
H
A string is a collection; a char is a single element inside that collection.
Valid char literals
char symbol = '!';
char numberChar = '5';
char space = ' ';
Any single Unicode character is valid. Choosing the more precise type (char for a single character, string for a collection) leads to better data modeling and clearer intent.