Ashokan Sivapragasam
Ashokan Sivapragasam

Reputation: 2189

Strange scenario Convert.ToChar(integer) or (char)integer

I have the following condition.

Console.WriteLine(Convert.ToChar(65)); // Gives 'A'

Console.WriteLine(Convert.ToChar(65) + 1); // Gives 66; Expectation was 'A1'

Console.WriteLine(Convert.ToChar(65) + "1"); // Gives 'A1'

Why is that? I wanted the 3rd case.

Upvotes: 2

Views: 556

Answers (4)

derpirscher
derpirscher

Reputation: 17382

Your expectation is wrong. The char type is a numeric type and can hold whole numbers. So when you do

Convert.ToChar(65)

you still have a number with the value 65. So when you do

Convert.ToChar(65) +1

You are implicitly converting the char back to an int and adding +1 thus you get 66

The special thing about char which distinguishes it from other number types is, when you convert it to string, it gets displayed as the "characters" we know from the alphabet. Thus, when you do

Convert.ToChar(65) + "1"

The char with value 65 is implicitly converted to a string ("A") and then concatenated with the string "1". Thus the result is "A1"

Upvotes: 5

Prasad Telkikar
Prasad Telkikar

Reputation: 16049

First Case:

Console.WriteLine(Convert.ToChar(65));

Above case is giving you result as A, because it is using Console.WriteLine(char) function.


Second Case

As per MSDN documentation:

A char can be implicitly converted to ushort, int, uint, long, ulong, float, double, or decimal.

Note: string type is not mentioned in the above implicit conversion list.

In your second example, the compiler is converting Convert.ToChar(65) i.e 'A' to integer implicitly and adding 1 to it and giving the result as 66 not A1


Third case

In your third example, you are concatenating char 'A' with string "1" using + operator which is printing "A1" as a string to the console.

Upvotes: 3

pho
pho

Reputation: 25489

From the documentation:

In the case of integral types, those operators (except the ++ and -- operators) are defined for the int, uint, long, and ulong types. When operands are of other integral types (sbyte, byte, short, ushort, or char), their values are converted to the int type, which is also the result type of an operation.

So in your second case, Convert.ToChar(65) gives 'A', but 'A' + 1 forces 'A' to the int type, which gives 65 + 1, which is 66.

Since string isn't an integral type, the + operator for that class is defined to append the character to the string, and you get the string "A1".

Upvotes: 4

Jawad
Jawad

Reputation: 11364

Reason you are getting 66 instead of A1 is because you are adding a char to an integer. If you add a string to char, only then it will return you a string.

documentation on char The char keyword is used to declare an instance of the System.Char structure that the .NET Framework uses to represent a Unicode character. The value of a Char object is a 16-bit numeric (ordinal) value

Upvotes: 8

Related Questions