vb.netoverflowexception

VB.NET OverflowException on very small operation


I'm trying to merge 2 colors and to do so I created a very simple function:

Public Function MixColors(color1 As Color, color2 As Color) As Color
    Dim a, r, g, b As Byte
    a = (color1.A + color2.A) \ 2
    r = (color1.R + color2.R) \ 2
    g = (color1.G + color2.G) \ 2
    b = (color1.B + color2.B) \ 2

    Return Color.FromArgb(a, r, g, b)
End Function

The problem is I get an OverflowException at the very first operation and I can't understand why.

I tried changing the type of the variables first to Integer and then to Double with no change in the results.

I also tried switching from the \ operator to the / one but still no change.

Does the type of the variables (color.A) influence the execution?


Solution

  • As Hans has already commented, if you add two bytes(like color1.A+color1.B) you get a byte as result which has a max value of 255. You have to cast it to Int32, for example with CInt. Color.FromArgb takes 4 integers anyway. So following should work:

    Dim a, r, g, b As Int32
    
    a = (CInt(color1.A) + CInt(color2.A)) \ 2
    r = (CInt(color1.R) + CInt(color2.R)) \ 2
    g = (CInt(color1.G) + CInt(color2.G)) \ 2
    b = (CInt(color1.B) + CInt(color2.B)) \ 2
    
    Return Color.FromArgb(a, r, g, b)