#76 – Arithmetic Operations with Small Integers

When doing arithmetic operations on variables of type byte, sbyte, short or ushort, the data values are first converted to int and the operations are performed on int types.

As an example, note that the following code does not compile.  You receive the compiler error “Cannot implicitly convert type ‘int’ to ‘byte’“.

 byte b1 = 5;
 byte b2 = 6;
 byte b3 = b1 + b2;

The problem is that the “b1 + b2” expression is evaluated as an int.  The two byte variables are first converted to int and the sum is calculated as an int.  But then we try to assign this int result back to a byte.  Because byte is smaller than int, we can’t do an implicit cast from int to byte.

We can avoid the compilation error by doing an explicit cast:

 byte b1 = 5;
 byte b2 = 6;
 byte b3 = (byte)(b1 + b2);
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: