C# Convert Int to Char

C# convert int to char google search is giving some result which I think is not directly what some people want. Most results are giving instructions on how to convert ascii code to char. If you want to know how to convert an int to char instead of ascii code, here is how you can do it.

If you try to cast an int to char you get the character asuming the integer is ascii code.

int a = 97;
char b = (char)a;
char c = Convert.ToChar(a); // Same as the line above
Console.WriteLine("output: " + b);
Console.WriteLine("output: " + c);

== Output ==
output: a
output: a

But we are not interested in the ascii code. We just want to convert the int to a char. Lets say the int is a one digit number. One way we could do it is by converting the int to a char array and take the first element. Since it is only one digit it will only be one element.

int a = 9;
char b = a.ToString().ToCharArray()[0];
Console.WriteLine("output: " + b);

== Output ==
output: 9

Since all strings are in reality a char array, we can shorten it like this.

int a = 9;
char b = a.ToString()[0];
Console.WriteLine("output: " + b);

== Output ==
output: 9

The C# Documentation about Char. Check out the C# Section.

One wayt of C# convert int to char. If there is a better or more correct way, let me know.

Related Posts

C# check if server is online

C# check if server is online directly from your code. Check servers or services like web servers, database servers like MySQL and MongoDB. You can probably check…

c# bash script

C# Bash Script Made Easy

There are many reasons why it could be handy to run a bash script from a C# application. In 2014, before I changed to a Mac as…

csharp ping check

C# Ping Check the easy way

How can we check if a computer, server, or another device is online? We can use a C# Ping check. If you can check the device with…

C# return index of a object

C# return index of a object in a List

How to return the index of a list type that is an object in C#. Most examples only shows simple string types when they show how to…

c# 99 bottles of beer

C# 99 bottles of beer on the wall

C# 99 bottles of beer on the wall is an easy programming challenge. The challenge can be solved in at least dozens of ways. Here is one…

C# Array find the first number above target

C# Array find the first number above target. If the array is sorted and you need to find the first number above your target number. Here is…

Leave a Reply