简体   繁体   中英

Convert integer to byte but do not overflow

How can I convert/cast an integer value to a byte value in C# but do not wrap around or throw an exception? What I'm looking for is some sort of bool byte.TryConvert(int i, out b) method.

I tried Convert.ToByte and direct casts.

byte b = Convert.ToByte(257); // throws OverflowException
byte b = (byte)257; // results in 1
byte b = (byte)(-1); // results in 255

Or do I have to "reverse-cast" (for lack of a better word) the byte to an int and compare it to the original value?

In my concrete use case I have in fact a nullable byte type. ... is there such a method as bool byte.TryConvert(int i, out b)?

No. You would have to do something like:

byte? result = (value >= byte.MinValue && value <= byte.MaxValue)
             ? (byte)value : (byte?)null;

Write the method yourself. Check the value of the int. If it is in range, return true and assign it to the out parameter with a direct cast. If not, return false, setting the out parameter to zero.

Downvoter please comment.

EDIT here's my solution; unlike Marc Gravell's, it does not introduce nullability:

public bool TryToByte(int value, out byte result)
{
    var success = value >= byte.MinValue && value <= byte.MaxValue;
    result = (byte)(success ? value : 0);
    return success;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM