Variables Variables are small areas in memory that you can use to store a value. This is very important in any programming language as you can imagine. � In C# it is quite simple to set up a variable. The syntax is as follows: � Variable-Type Variable-Name; � This will set up the variable of a selected type with the name you wish. Here's an example: � int myNumber; � This has set up an integer variable called myNumber. While setting up a variable it is good to set5 a default value as from time to time there might be some "junk" in it and its good to make sure its a clean variable. So we'll make our number = 0 while we set it up. � int myNumber = 0; � � Now we have an integer variable with the number 0 in it so lets output this to the screen. � To output a variable we do the same as the Hello World program, except in the Console.WriteLine part we won't use any " and will just type the variable name: � int myNumber = 0; Console.WriteLine(myNumber); Console.ReadLine(); � Now if you run that you should see that the number 0 will show on the screen. Now change the number to 100: int myNumber = 100; � Now the screen should show 100. � Now we'll create a new variable called myString of the type string. So below your integer add this line: string myString = "Hello World"; � And we'll add this as an output too so add this line below our first WriteLine: Console.Write(myString); � Now we have 2 variables and 2 outputs. Well done you now know how to assign and output variable but what if you want to change them? Simple enough, add this after all the Console.Write statements. � myNumber = 99; myString = "Hello Universe"; Console.WriteLine(myNumber); Console.WriteLine(myString); � You should see that when you run it that the first 2 lines are your original variables and the next 2 are your new assignments. How easy was that? � Next up we'll be learning how to use different operators such as adding, subtracting and also how to output several variables at once. So if your still interested in C# get your butt over to Chapter 4. �
|