Data Type Conversions

From TRCCompSci - AQA Computer Science
Revision as of 08:04, 20 May 2024 by Admin (talk | contribs) (Created page with "Data types in C# are very strict, and you will need to convert the data type when required. ==Convert== For example if you wanted to read in an integer from the keyboard, you...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Data types in C# are very strict, and you will need to convert the data type when required.

Convert

For example if you wanted to read in an integer from the keyboard, you need to convert the string to an integer. This can be done like this:

Console.WriteLine("HelloWorld");
int Age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Hola Mundo, you are" + Age);
Console.WriteLine("You will be "+ (Age+1) + " at your next birthday");

So using 'Convert.ToInt32()' will do the conversion. 'Convert' can also convert many other data types.

Casting

Casting converts the value during runtime and is only temporary, once the casting takes place the value will revert to the original state:

 double a = 3452.345; 
 int b = 0; 
  
 // type conversion 
 b = (int)a; 
  
 Console.WriteLine(b);