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.

About Author

Related Posts

C# Reference Types

Understanding C# Reference Types

One of the key features of C# is its support for C# reference types, which allow developers to create complex, object-oriented applications. In this blog post, we…

c# value types

Understanding C# Value Types

C# is a powerful programming language that is widely used for developing a wide range of applications. One of the key features of C# is its support…

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…

Leave a Reply