Click here to Skip to main content
15,029,958 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everybody.
would you tee tell me please why we cant write this code:
string message="Enter Number 1: ";
string message2 = "Enter Number 2: ";
Int16 num1, num2, sum, product;
num1 = Convert.ToInt16(Console.ReadLine());

Console.WriteLine("You entered : "+ num1);
num2 = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("You entered : " + num2);
sum = num1 + num2;
product = num1 * num2;
                  "sum = ", sum, "Product = ", product,
                  "Sum * Product = ",sum*product);

actually my problem is :
when we declare an int16 variable like "sum" it can't store summation of two int16 variables?
but if our variables declare as int, there is no problem with them.
and i know we must use it like this
sum = (Int16)(num1+num2);

but explain me complete please.
thank you all friends.

As you already know:
sum = (Int16)(num1 + num2);
product = (Int16)(num1 * num2);

will work. (unless the result is greater than Int16.MaxValue (32.768))

The arithmetic operators (+, −, *, /, %) are defined for all numeric types except the 8- and 16-bit integral types. Int16 is a 16 bit integral. So if you multiply two Int16 (or Int8 etc) a 32bit arithmetic operator is used. And that is why the result is a Int32.

Operator for the "biggest" datatype is always used. If you add a 16Bit value and a 32bit value it will return a 32bit value. If you multiply a 32bit value and a 64bit value it will return a 64bit value.

some examples:
Int16 + Int32 = Int32
Int16 + Int64 = Int64
Int32 * Int32 = Int32
Int32 * Int64 = Int64
Abolfazl Beigi 20-Jul-12 12:15pm
Thanks for your answer, but why if we declare a Int32 variable as 'sum' and it used to store sum= num1(Int32) + or * num2(Int32), there is not any problem?
it means why for calculate this summation or product is not needed an Int64 variable? is the result less than 32 bit or not? explain me please. thanks again.
StianSandberg 20-Jul-12 14:46pm
Operators are defined for all numeric types exept 8 and 16 bit. So if you use an operator the return value cannot be a 8 or 16 bit int. It will be returned as Int32.
I've updated my answer to explain more detailed.
Abolfazl Beigi 20-Jul-12 16:31pm
Thank you very much dear friend.

I think this is a problem with Operator Overloading, when operator perform its job it return an inter value as Int16 is required less memory space then Int32 so it cant be cast directly you may use some custom Implicit or Explicit casting
or Use
to Convert it.

there for it cant be directly cast so its throwing an error.

But when you declare Int then its work.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900