-
__box problem
I am reading into Managed C++, came across this code
Code:
#using <mscorlib.dll>
using namespace System;
int main()
{
double salary = 12.84;
Console::Write("Salary: ");
Console::WriteLine(__box(salary));
Console::WriteLine();
return 0;
}
It was said that Write and WriteLine that we have used so far expect a specific type of value. To convert a regular type to this type of value, Managed C++ provides a unary operator called __box. This operator uses parentheses in which you type the value that needs to be converted.
So I tried this
Code:
#using <mscorlib.dll>
using namespace System;
int main()
{
double salary = 12.84;
Console::Write("Salary: ");
Console::WriteLine(salary);
Console::WriteLine();
return 0;
}
This also works fine....then why do I need to use __box.
-
There's probably an automatic conversion that is performed. However, in programming it is always better to make what is happening explicit in your code, so someone reading your code can easily understand it. For instance, in C++ you can assign a double(a number with a decimal point) to an int type:
Code:
int n = 0;
double d = 3.5;
...
...
n = d;
But, since an int is a whole number, the .5 is truncated and n is set equal to 3. That is an automatic conversion that takes place. However, when you are reading the code, you may mistakenly think n=3.5. So, it's better to make the conversion explicit by casting the double to an int before assigning it to n:
Code:
int n = 0;
double d = 3.5;
...
...
n = static_cast<int>(d);
Now, that ugly cast syntax really sticks out and warns the reader that something is happening to d before it is assigned to n.