Casting As everything from the keyboard in C# is viewed as a string by the compiler, we need to cast our input into the correct data type. Some languages do this automatically (such as Python)! Sadly, in C# we have to do this manually. Pseudocode Variables can be typecast using the int str and str(3) returns "3" float functions. int("3") returns 3 float("3.14") returns 3.14 C# Here we have option to cast from //Variables strings to numerical data types and string userEntry = "54"; from numerical data types back to a string. int castNumber; double dblNumber; The output is shown below: string backToString; //Various casting options castNumber = int.Parse(userEntry); As we can see it makes no different dblNumber = double.Parse(userEntry); to the printing to screen but it does – allow us to now carry out calculations backToString = Convert.ToString(dblNumber); on the numeric data types such as multiplication and division. //Printing the output Console.WriteLine(userEntry); Console.WriteLine(castNumber); Console.WriteLine(dblNumber); Console.WriteLine(backToString); Random numbers It is possible to generate a random number in C# for use within a program. As the radom generator is method Random randomGenerator = new Random(); within a pre-defined class, we have to create an instance of this method int myRandomNumber = randomGenerator.Next(0, first. 100); Next we can assign a random number to a variable, using the
Casting As everything from the keyboard in C# is viewed as a string by the compiler, we need to cast our input into the correct data type. Some languages do this automatically (such as Python)! Sadly, in C# we have to do this manually. Pseudocode str(3) returns "3" int("3") returns 3 float("3.14") returns 3.14 Variables can be typecast using the int str and float functions. C# //Variables string userEntry = "54"; int castNumber; double dblNumber; string backToString; //Various casting options castNumber = int.Parse(userEntry); dblNumber = double.Parse(userEntry); backToString = Convert.ToString(dblNumber); //Printing the output Console.WriteLine(userEntry); Console.WriteLine(castNumber); Console.WriteLine(dblNumber); Console.WriteLine(backToString); Here we have option to cast from strings to numerical data types and from numerical data types back to a string. The output is shown below: As we can see it makes no different to the printing to screen – but it does allow us to now carry out calculations on the numeric data types such as multiplication and division. Random numbers It is possible to generate a random number in C# for use within a program. Random randomGenerator = new Random(); int myRandomNumber = randomGenerator.Next(0, 100); As the radom generator is method within a pre-defined class, we have to create an instance of this method first. Next we can assign a random number to a variable, using the