3

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?

7
  • Perhaps a stupid question, but what stops you from just checking if your int is greater than 255 before doing a cast? Commented Sep 11, 2014 at 7:23
  • 2
    What is your intended result? (and surely the result of that cast from 256 (pre-edit) is 0, not 1?) Commented Sep 11, 2014 at 7:24
  • @MarcGravell: intended result is 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). Commented Sep 11, 2014 at 7:27
  • 1
    It's not obvious from your question what result you want for the cases were the integer is outside the range 0 - 255. Commented Sep 11, 2014 at 7:28
  • @knittl null is not a valid value for byte, so you can't do that; you'd need to use byte? or similar Commented Sep 11, 2014 at 7:28

3 Answers 3

7

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;
Sign up to request clarification or add additional context in comments.

3 Comments

"is there such a method as bool byte.TryConvert(int i, out b)?" - there is now. :-)
Looks good (not as contrived as my solution), thanks! :) why cast value to byte and not a nullable byte? Is there a difference between ? (byte?)value : null and ? (byte)value : (byte?)null? I know that .NET sometimes generates weird (iow inefficient) IL code when nullable primitive types are involved.
Yup, just verified with LINQPad that two casts will result in less IL instructions than the version with a single cast to byte?
2

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;
}

2 Comments

@Alex I did not include an example because it seemed to me that this was a bit of a "please write my code for me" question.
Ah, more downvotes. I've now added the method I had in mind when I wrote this answer.
0

If you don't want the int to "overflow" to another value but stays in the range of a Byte, e.g. if < 0 then results 0, and if > 255 then results 255, else stays the same. Just add a Clamp before converting.

(byte)Mathf.Clamp(yourIntValue, 0, byte.MaxValue)

You can use this to other types of course. If you're sure the min value of the type, then you can change 0 to the type's MinValue. For example:

(sbyte)Mathf.Clamp(yourIntValue, sbyte.MinValue, sbyte.MaxValue)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.