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?
null(for my usecase). A method which returns true if casting/conversion was successful and false for failed conversions would be best (if such a function already exists in the .NET framework).nullis not a valid value forbyte, so you can't do that; you'd need to usebyte?or similar