Implicit type cast of char to int in C#

Viewed 7792

I have a question about the implicit type conversion

Why does this implicit type conversion work in C#? I've learned that implicit code usually don't work.

I have a code sample here about implicit type conversion

 char c = 'a';
 int x = c;
 int n = 5;
 int answer = n * c;
 Console.WriteLine(answer);
9 Answers

The core of @Eric Lippert's blog entry is his educated guess for the reasoning behind this decision of the c# language designers:

"There is a long tradition in C programming of treating characters as integers 
-- to obtain their underlying values, or to do mathematics on them."

It can cause errors though, such as:

var s = new StringBuilder('a');

Which you might think initialises the StringBuilder with an 'a' character to start with, but actually sets the capacity of the StringBuilder to 97.

Related