TOC

This article is currently in the process of being translated into Danish (~9% done).

The Basics:

Variables

En variabel kan sammenlignes med et opbevaringsrum og er essentiel for programmøren. I C# deklareres en variabel sådan her:

<data type> <navn>;

Her er et eksempel på hvordan det kan se ud:

string navn;

Det er den mest grundlæggende version, men variablen har endnu ikke en værdi. Du kan tildele en værdi senere i koden eller på samme tidspunkt som erklæringen, som vist her:

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

If this variable is not local to the method you're currently working in (e.g. a class member variable), you might want to assign a visibility to the variable:

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

And a complete example:

private string name = "John Doe";

The visibility part is related to classes, so you can find a more complete explanation of it in the chapter about classes. Let's concentrate on the variable part with an example where we actually use 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 ask the user to enter a new first name, and then we use the ReadLine() method to read the user input from the console and enter it 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:

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();

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.

Variables & scope

So far, we have only used local variables, which are variables defined and used within the same method. In C#, a variable defined inside a method can't be used outside of this method - that's why it's called local. If you're familiar with other programming languages, you may also know about global variables, which can be accessed from more places, but C# doesn't support the concept of global variables. Instead, you can define a field on a class, which can be accessed from all the methods of this class. Allow me to demonstrate this with an example:

using System;

namespace VariableScope
{
    class Program
    {
private static string helloClass = "Hello, class!";

static void Main(string[] args)
{
    string helloLocal = "Hello, local!";
    Console.WriteLine(helloLocal);
    Console.WriteLine(Program.helloClass);
    DoStuff();
}

static void DoStuff()
{
    Console.WriteLine("A message from DoStuff: " + Program.helloClass);
}
    }
}

Notice the helloClass member, declared on the class scope instead of inside a method - this will allow us to access it from both our Main() method as well as our own DoStuff() method. That is not true for our helloLocal variable, which has been declared inside the Main() method and can therefore only be used inside of this specific method.

The concept of differentiating between where a variable has been declared is called scoping and it prevents your code from becoming a huge mess of variables which can be changed from too many places. Another technique that helps us with this is called member visibility (in this case illustrated with the private keyword), which we'll discuss in the chapter about classes.

Summary

Variables allow you to store data of various types, e.g. text strings, numbers or custom objects. There are local variables, which are accessible inside of the method in which it has been defined, and then there are class fields, which can be accessed from all the methods of the class and even outside of the class, if the visibility permits it.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!