3 Sept 2013

How to create variable in c#

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:
private string name = "John Doe";
The visibility part is explained elsewhere in this tutorial, so let's concentrate on the variable part. We will jump straight to an example of actually using a couple of them:
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string firstName = "John";
            string lastName = "Doe";

            Console.WriteLine("Name: " + firstName + " " + lastName);

            Console.WriteLine("Please enter a new first name:");
            firstName = Console.ReadLine();

            Console.WriteLine("New name: " + firstName + " " + lastName);

            Console.ReadLine();
        }
    }
}
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. 

No comments:

Post a Comment

How to Create WEBSITE DESIGN

Way2finder Technologies is a web design studio that offers corporate web design and custom web design. Our website designers offer cheap w...