← 返回课程: C# from scratch

Variables and data types

视频即将上线

A variable is a name that points to a value stored in memory. C# is statically typed: every variable has a type that is decided when you write the code and never changes. This lets the compiler stop you before running if you try, for example, to store text where a number belongs.

The basic types

  • int: whole numbers (roughly -2.1 billion to 2.1 billion). Example: 42.
  • long: much larger whole numbers. Example: 9000000000L.
  • double: general purpose decimals. Example: 3.14.
  • decimal: exact decimals, ideal for money. Example: 19.99m.
  • bool: true or false.
  • char: a single character between single quotes. Example: 'A'.
  • string: text between double quotes. Example: "hello".

Notice the suffixes: 19.99m means decimal and 9000000000L means long. Without a suffix, a number with a dot is taken as a double. The difference matters: double stores binary approximations (0.1 + 0.2 is not exactly 0.3), while decimal stores the exact decimal value, which is why it is used for prices and balances.

csharp
string name = "Ana";
int age = 29;
double height = 1.68;
decimal balance = 1250.75m;
bool isStudent = true;
char grade = 'A';

Console.WriteLine(name);
Console.WriteLine(age);
Console.WriteLine(height);
Console.WriteLine(balance);
Console.WriteLine(isStudent);
Console.WriteLine(grade);

Console.WriteLine(0.1 + 0.2);       // 0.30000000000000004
Console.WriteLine(0.1m + 0.2m);     // 0.3

var, const and changing values

With var you ask the compiler to infer the type from the initial value. It is not dynamic typing: the variable still has a fixed type, you just do not write it. Use it when the type is obvious from the right side of the assignment. With const you declare a value that never changes and must be known at compile time.

csharp
var count = 10;            // int
var price = 4.5m;          // decimal
var title = "C# course";   // string
const double Pi = 3.14159;

count = count + 5;         // count is now 15
count += 1;                // shortcut: now 16
count++;                   // adds 1: now 17

// count = "ten";          // ERROR: cannot assign string to int
// Pi = 3;                 // ERROR: a const cannot change

Console.WriteLine($"count={count}, price={price}, title={title}, Pi={Pi}");

Naming rules

A variable name starts with a letter or underscore, cannot contain spaces or be a reserved word (like int or class) and is case sensitive. The C# convention is camelCase for local variables (totalPrice) and PascalCase for constants and your own types (MaxItems). Choose names that explain the content: customerAge is better than x.

Mind the limits

Each type has a range. If you add one to the maximum value of an int, the result wraps around and becomes negative, without warning. To see the limits use int.MaxValue and int.MinValue. When you need larger numbers, switch to long. Also remember that a variable must have a value assigned before it is used: the compiler refuses to read an uninitialized variable.

csharp
int big = int.MaxValue;
Console.WriteLine(big);        // 2147483647
big++;
Console.WriteLine(big);        // -2147483648 (wrapped around)

long safe = int.MaxValue;
safe++;
Console.WriteLine(safe);       // 2147483648

One last detail: C# converts by itself and without risk from a smaller type to a larger one (an int fits in a long or a double), but not the other way around. If you try to store a double in an int, the compiler stops you, because the decimals would be lost. Later you will see how to ask for that conversion explicitly, accepting the loss. In the meantime, pick the right type from the start and you will avoid most of these warnings.

✎ 我的笔记

仅保存在此浏览器中。登录后可保存到账号。0/5000 字符

← 上一节下一节 →