計算機科学のブログ

data, types, objects, and references - Managing your app's data - Casting lets you copy values that C# can't automatically convert to another type

Head First C Sharp: A Learner’s Guide to Real-World Programming with C Sharp and .NET (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)の Chapter 4(data, types, objects, and references - Managing your app’s data)、p.195(Sharpen your pencil)の解答を求めてみる。

コード

Program.cs

int myInt = 10;
byte myByte = (byte)myInt;
double myDouble = (double)myByte;
// bool myBool = (bool)myDouble;
string myString = "false";
// bool myBool = (bool)myString;
// myString = (string) myInt;
myString = myInt.ToString();
// bool myBool = (bool)myByte;
bool myBool = false;
// myByte = (byte)myBool;
short myShort = (short)myInt;
char myChar = 'x';
// myString = (string)myChar;
long myLong = (long)myInt;
decimal myDecimal = (decimal)myLong;

myString = myString + myInt + myByte + myDouble + myChar;

Console.WriteLine(myString);
Console.WriteLine(myBool);
Console.WriteLine(myShort);
Console.WriteLine(myDecimal);

入出力結果(Terminal, Zsh)

10101010x
False
10
10