3

I have this code and it doesn't work for some reason. I don't understand it. What is wrong?

byte dog = (byte)2*byte.Parse("2");

I get this exception in LinqPad: "Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)."

Also what is the right way to write this code? Thanks.

VMAtm
  • 27,943
  • 17
  • 79
  • 125
Beta
  • 87
  • 7

3 Answers3

2

Multiplying a byte value with another byte value will for most of the possible outcomes render a value that doesn't fit in a byte. The extreme case is the max value product 255 * 255 - while each factor fits in a byte, the product needs an integer to fit.

Johann Gerell
  • 24,991
  • 10
  • 72
  • 122
2

All arithmetic operations on sbyte, byte, ushort, and short are widened to int. For example, the third line will give compiler error:

byte b1 = 1;
byte b2 = 2;
byte b3 = (b1 * b2); // Exception, Cannot implicitly convert type 'int' to 'byte
byte b4 = (byte)(b1 * b2); // everything is fine

So, change your code as:

byte dog = (byte)((byte)2*byte.Parse("2"));

For more information: Look at this SO question

Community
  • 1
  • 1
Farhad Jabiyev
  • 26,014
  • 8
  • 72
  • 98
0

That's because, from compilator opinion, you're trying to cast to the byte only first multiplier, not the whole result. This is because of operators precedence in c#

Try this:

byte dog = (byte) (2*byte.Parse("2"));

Also you should note that you can got an integer bigger than maximum byte value (which is a const equal to 255, and there will be a loss of data by such type conversion.

VMAtm
  • 27,943
  • 17
  • 79
  • 125