Confused with type conversions!

VitzzViperzz

Well-known member
Joined
Jan 16, 2017
Messages
75
Location
United Kingdom
Programming Experience
1-3
So I was following this book and it was okay, then it shows an example of a few conversions and I get confused.

C#:
ushort destinationVar;char sourceVar = 'a';
destinationVar = sourceVar;
WriteLine($"sourceVar val: {sourceVar}");
WriteLine($"destinationVar val: {destinationVar}");

So we are converting a few values between each other and then printing the value to the console, but it says this is the output:

C#:
sourceVar val: a
destinationVar val: 97

I don't quite understand it. Where did we get the 97 from? Don't we lose the value of sourceVar if we are converting the value? How has he still managed to print its initial value?


If I could get an explanation, that would be great.
 
Where did we get the 97 from?
97 is the Unicode point value - and also the ASCII code - for the character 'a'. All data in computers is stored as bytes and it's then up to the computer and its software to interpret those bytes based on the type of the data. When you store character data, it is stored as bytes that represent either the ASCII or Unicode values of those characters. In this case, the number 97 is actually stored in the memory backing that 'sourceVar' variable but, because your variable is type 'char', it gets interpreted as a character rather than a number. Once that value is stored in the 'destinationVar' variable though, it gets interpreted as a number because that variable is type 'ushort', which is a numeric type.
Don't we lose the value of sourceVar if we are converting the value? How has he still managed to print its initial value?
The values of those two variables are stored in two different memory locations. An assignment from a variable has exactly zero impact on that variable. 'sourceVar' still contains exactly what it contained before after performing the assignment. 'destinationVar' on the other hand, contains a copy of what was in 'sourceVar' at the time.
 
Back
Top Bottom