• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 659
  • Last Modified:

Decrease Int16 variable with 1

Why does I get the error "Cannot convert type int to short" when doing like this:

Int16 test = 100;
test = test - 1;


This works, but I need to know why the code above fails:

Int16 test = 100;
test--;

(test is 99)
0
webressurs
Asked:
webressurs
  • 4
  • 3
2 Solutions
 
chapmanjwCommented:
In code "1" is an Int32 I believe.

Try one of these:

Int16 test = 100;
Int16 test2 = 1;
test = test - test2;

Or

Int16 test 100;
test = test - (Int16)1;

or

Int16 test 100;
test = test - Convert.ToInt16(1);
0
 
chapmanjwCommented:
By the way, short in C# = Int16 and int in c# = Int32.
0
 
webressursAuthor Commented:
Get the same error ("Cannot convert type int to short") on this:

Int16 test = 100;
Int16 test2 = 1;
test = test - test2;

...and this:

Int16 test = 100;
test = test - (Int16)1;

...and this:

Int16 test = 100;
test = test - Convert.ToInt16(1);
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
chapmanjwCommented:
Sorry, wasn't in front of a machine where I could test it ;-P

But, this should work:

short test 100;
test = test - (short)1;
0
 
webressursAuthor Commented:
Still same error here... Hmmm :)
But, I changed the variable to int and that works good enought:

int test = 100;
test = test - 1;
0
 
chapmanjwCommented:
Ok.  

The reason Int in C# equates to an Int32, is because it is the most used variation of an integer.

You would only really need to use shorts (Int16) or longs (Int64) if you had a requirement to work with a database that specified them.  Otherwise, it doesn't really affect anything to simply use Int (Int32).
0
 
jhshuklaCommented:
http://msdn.microsoft.com/en-us/library/ybs77ex4.aspx

According to the above link, the result of adding two shorts is an int. So use the following:

test = (short)(test - 1);
0
 
webressursAuthor Commented:
Thank you!
0

Featured Post

[Webinar On Demand] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now