Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with this expression? Cannot implicitly convert type 'int' to 'byte'

Tags:

c#

I am getting the error "Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)". Doesn't byte + byte = byte? Also I notice when I remove the +rgb.Green it works

// rgb.Red, rgb.Green, rgb.Blue are byte types
// h, delta are double
rgb.Red = Convert.ToByte(Math.Round((h - 4) * delta)) + rgb.Green;

public struct RGBColor
{
    public byte Red { get; set; }
    public byte Green { get; set; }
    public byte Blue { get; set; }
}
like image 683
Jiew Meng Avatar asked Nov 08 '10 12:11

Jiew Meng


2 Answers

Adding two bytes produces an integer in C#. Convert the entire thing back to a byte.

rgb.Red = (byte)(Convert.ToByte(Math.Round((h - 4) * delta)) + rgb.Green);

See byte + byte = int... why? for more information.

like image 111
Pieter van Ginkel Avatar answered Oct 10 '22 10:10

Pieter van Ginkel


Doesn't byte + byte = byte?

Nope, because it may overflow (> 255), that's why this operation returns an Int32. You could cast the result back to byte at your own risk.

like image 22
Darin Dimitrov Avatar answered Oct 10 '22 09:10

Darin Dimitrov