Wednesday, 12 November 2014

C#.NET Tutorial - Day - 4 - The Basics - Variables


VARIABLES



A variable can be compared to a storage room, and is essential for the programmer. In C#, a variable is declared like this: 

<data type> <name>; 

An example could look like this: 

string name; 

That's the most basic version. Usually, you wish to assign a visibility to the variable, and perhaps assign a value to it at the same time. It can be done like this: 

<visibility> <data type> <name> = <value>; 

And with an example:




The visibility part is explained elsewhere in this Blog, so let's concentrate on the variable part. We will jump straight to an example of actually using a couple of them:





Okay, a lot of this has already been explained, so we will jump directly to the interesting part. First of all, we declare a couple of variables of the string type. A string simply contains text, as you can see, since we give them a value straight away. Next, we output a line of text to the console, where we use the two variables. The string is made up by using the + characters to "collect" the different parts. 

Next, we urge the user to enter a new first name, and then we use the ReadLine() method to read the user input from the console and into the firstName variable. Once the user presses the Enter key, the new first name is assigned to the variable, and in the next line we output the name presentation again, to show the change. We have just used our first variable and the single most important feature of a variable: The ability to change its value at runtime

Another interesting example is doing math. Here is one, based on a lot of the same code we have just used:




Put this in our Main method, and try it out. The only new "trick" we use here, is the int.Parse() method. It simply reads a string and converts it into an integer. As you can see, this application makes no effort to validate the user input, and if you enter something which is not a number, an exception will be raised. More about those later.



No comments:

Post a Comment