Sergiodela
Sergiodela

Reputation: 43

How to store and represent an int value as a char (C#)

Im not sure if the title is well explained. What I mean is getting this done:

int i = 3;
char id = (char)i:
Console.Writeline(i);
Console.Writeline(id);

and then getting the output in Console:

3

3

But (obviously) I get the output:

enter image description here

I would like to be able to store as a character the same value of the int variable, not the associated symbol code.

Upvotes: 2

Views: 1239

Answers (3)

DennisS
DennisS

Reputation: 1

You could convert the int value to a string first. If you still need it as a char, you can just place the string value inside a char variable by converting it. It would look like that:

int number = 3;
 string convertedNumber = Convert.ToString(number);
 char getChar = Convert.ToChar(convertedNumber);
 Console.WriteLine(getChar);

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062865

Assuming you mean an integer in the range 0 thru 9, then offset the value by the character code for the zero character in ASCII - which happens to be 48, but there's no need to know that here - just use the character itself:

int i = 3;
char id = (char)('0' + i);

If you mean any integer: ToString() is your friend (there isn't a char that can display the value of 42 or -3, for example, since they need multiple characters).

Upvotes: 4

Martin Verjans
Martin Verjans

Reputation: 4796

i.ToString() is what you are looking for.

(char)i converts the value using the ASCII tables, 3 meaning ETX - End of TeXt and therefore showing you a weird symbol.

Upvotes: 2

Related Questions