Книга: C# 2008 Programmer

Variables

Variables

In C#, you declare variables using the following format:

datatype identifier;

The following example declares and uses four variables:

class Program {
 static void Main(string[] args) {
  //---declare the variables---
  int num1;
  int num2 = 5;
  float num3, num4;
  //---assign values to the variables---
  num1 = 4;
  num3 = num4 = 6.2f;
  //---print out the values of the variables---
  Console.WriteLine("{0} {1} {2} {3}", num1, num2, num3, num4);
  Console.ReadLine();
  return;
 }
}

Note the following:

num1 is declared as an int (integer).

num2 is declared as an int and assigned a value at the same time.

num3 and num4 are declared as float (floating point number)

? You need to declare a variable before you can use it. If not, C3 compiler will flag that as an error.

? You can assign multiple variables in the same statement, as is shown in the assignment of num3 and num4.

This example will print out the following output:

4 5 6.2 6.2

The following declaration is also allowed:

//---declares both num5 and num6 to be float
// and assigns 3.4 to num5---
float num5 = 3.4f, num6;

But this one is not allowed:

//---cannot mix different types in a declaration statement---
int num7, float num8;

The name of the variable cannot be one of the C# keywords. If you absolutely must use one of the keywords as a variable name, you need to prefix it with the @ character, as the following example shows:

int @new = 4;
Console.WriteLine(@new);

Оглавление книги

Оглавление статьи/книги

Генерация: 0.056. Запросов К БД/Cache: 0 / 2
поделиться
Вверх Вниз