Is there a way to format an integer as the equivalent ASCII/Unicode character in C#? For example, if I have the following code:
int n = 65;
string format = ""; // what?
string s = string.Format(format, n);
what do I need to put in the string format
to result a single character, 'A', being written to s
- basically I'm looking for the equivalent of doing the following in C:
int n = 65;
char s[2];
char format = "%c";
sprintf(s, format, n); /* s <- 'A' */
EDIT
I should probably explain a bit more about what I'm trying to do, as the obvious answer "cast it to char", doesn't help.
I have a situation where I have an integer value that represents a bank account check digit, but which needs to be output as a character for some countries and a (0-padded) digit string for others. I'm wondering if there's a way of switching between the two just by changing the format string, so I can hold a dictionary of the appropriate format strings, keyed on the country code.
EDIT 2
(For Oded) something like this ...
IDictionary<string, string> ccFormat = new Dictionary<string, string>()
{
{ "GB", "{0:D}" }, // 0-9
{ "PT", "{0:D2}" }, // 00-99
{ "US", "{0:D3}" }, // 000-999
{ "IT", ???? } // A-Z -- What should ???? be?
};
string FormatCheckDigits(int digits, string country)
{
return string.Format(ccFormat[country], digits);
}
Currently I've got ????
as null
and some special case code in the method:
string FormatCheckDigits(int digits, string country)
{
string format = ccFormat[country];
if (string.IsNullOrEmpty(format))
{
// special case: format as A-Z
return ((char) digits).ToString();
}
else
{
// Use retrieved format string
return string.Format(format, digits);
}
}