6
Why a var
of the kind double
can store a var
of the kind int
?
Using C#
int x;
double y;
x = 5;
y = 2*x;
Console.WriteLine(x);
Console.WriteLine(y);
Console.ReadLine();
6
Why a var
of the kind double
can store a var
of the kind int
?
Using C#
int x;
double y;
x = 5;
y = 2*x;
Console.WriteLine(x);
Console.WriteLine(y);
Console.ReadLine();
7
Let’s start calling things by the right name, then let’s call x
and y
variable, because var
is a C# command and using that word can confuse what you’re talking about.
Then at the end I’d be saying
a variable of type
double
can store a variable of typeint
Then I’ll correct the term once again, it’s meant to say:
a variable of type
double
can store a value of typeint
Variable is one thing, value is another.
It turns out that a value of the type is not being stored int
in y
. The type of value stored there will always be of the type double
because C# is a static typing language and the variable can only have a value of the type it was declared. Well, there is the question of null
, but let’s leave it there so as not to confuse because in this case can not have this value.
So what happened? There was one cast implicit. Had a multiplication of two values of type int
(2
and x
) and the result of that which is also int
is automatically converted to a value of the type double
. Then effectively a value reconstruction operation in another format is performed (since int
and double
sane internally incompatible), even if it doesn’t seem to have it.
Automatic conversion is possible only in cases that have no data loss, and as whole value of int
is a valid value in double
the conversion is placed by the compiler.
Congratulations on your curiosity, just get used to using correct terms to communicate properly.
Oops man, thank you for being contributing to my learning. This issue of data loss I’ve come to see in the course I’m taking. But, to be more clear, what would be this data loss ?
Let’s take the opposite, you want to store 1.4 which is double
in a variable of type int
, then you have to save 1 since you can only store decimal part in this type, and where did 0.4 go? There is a loss. You’re allowed to do this, but only manually, you have to say that you want the loss, the compiler doesn’t do it for you. If solved, you can accept the answer, see how it is in [tour].
So in this case I can make an explicit casting ? type double x = 1.4; int y = (int) x;
Can yes, you said you want the loss.
All right, thanks man.
@Fluss you read the [tour]? understood what you should do?
Browser other questions tagged c# .net typing type-conversion
You are not signed in. Login or sign up in order to post.
Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site.
– Maniero