How can (byte)Convert.ToChar(anyStringOfLengthOne) possibly throw an error?

We have this rather simple code in a project:

string input = "Any string";
for (int i = 0; i < input.Length; i++)
{
    string stringOfLengthOne = input.Substring(i, 1);
    byte value = (byte)Convert.ToChar(stringOfLengthOne);
    if (value == someValue)
    {
        // do something
    }
}

The input is a string with characters usually read from a file that need to be processed depending on their byte value.

Unfortunately, we do not have the chance to debug this process step-by-step, we just need to make an educated guess what kind of string could cause

 (byte)Convert.ToChar(anyStringOfLengthOne)

in the code above to throw an "Arithmetic operation resulted in an overflow" error.

My thinking is that as soon as I have a string, it should always be possible to 1. pick a char and 2. convert it to a byte. Yet the error occurs.

Any ideas, hints? Or can someone even provide a string that throws this kind of error?

Answers


Characters in .Net are 16 bits (short/ushort) in length.

The default project settings for C# means that the cast would work and will just ignore the higher bits for any character that is larger than 255, i.e. like using (byte) (c & 0xff).

However, if you are using checked arithmetic, trying to cast a char that is greater than 255 will result in an ArithmeticOverflowExcetion.

The default setting for arithmetic can be set to checked/unchecked in the project's build settings.

Example

char c = (char) 300;
byte b = unchecked ((byte) c);
Console.WriteLine (b);

// Result: 44

char c = (char) 300;
byte b = checked ((byte) c);
Console.WriteLine (b);

// Result: ArithmeticOverflowExcetion

Alternative

Alternativly, you could compare the characters directly.

For example to test if a character is 0-9

char c = input[i];
if (c >= '0' && c <= '9') {
    // do something
}

You can even compare a char to an int

char c = input[i];
if (c >= 48 && c <= 57) {
    // do something
}

Need Your Help

Writing to the Windows Event Log from ASP.NET with a custom app pool account

c# asp.net

I am trying to write to the windows event log from ASP.net. The app pool is running under a domain account rather than Network Service.

using cin to close a while loop

c++ while-loop

I'm trying to verify my user input using a while loop. Please see below for my code/while loop. I want them to enter a float number, and I'm trying to verify that they have entered a number rather ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.