Variables 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: 

Syntax - 

<data type> <name>; 


An example could look like this: 

string name; 

This is the most basic version. Normally, you want to assign visibility to variables, and possibly can specify a value at the same time. This can be done:


Syntax - 

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



private string name = "John Doe";
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 has already been explained, so we will jump straight to the interesting part. First of all, we declare some variables of string type. There is just a text in a string, as you can see, because we give them direct value. After this, we produce a line of text to the console, where we use two variables. The string is created using the + letters to "collect" various 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 again, to show the change. We have just used our variable and the most important feature of a variable: The ability to change its value at runtime.



int number1, number2;

Console.WriteLine("Please enter a number:");
number1 = int.Parse(Console.ReadLine());

Console.WriteLine("Thank you. One more:");
number2 = int.Parse(Console.ReadLine());

Console.WriteLine("Adding the two numbers: " + (number1 + number2));

Console.ReadLine();
Keep it in our main method, and try it out. The only new "move" that we use here, it is the int.Parse () method. It only reads a string and converts it into an integer. As you can see, this application does not make any efforts to validate user input, and if you enter something that is not a number, exceptions will be raised. More about them later.





Share on Google Plus

About It E Research

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment