A variable is simply the name of a storage area for the program to operate on. In C#, each variable has a specific type, which determines the memory size and layout of the variable. Values within the range can be stored in memory and a series of operations can be performed on variables.
We have discussed various data types. The basic value types provided in C# can be broadly divided into the following categories:
Types | Give an example |
|---|---|
Integer type | Sbyte, byte, short, ushort, int, uint, long, ulong and char |
Floating point type | Float and double |
Decimal type | Decimal |
Boolean type | True or false value, specified valu |
Null type | Data types that can be nullable |
C# allows you to define variables of other value types, such as C# syntax for variable definition Here, Some valid variable definitions are as follows: You can initialize when a variable is defined: Variables are initialized (assigned) by an equal sign followed by a constant expression. The general form of initialization is: Variables can be initialized when declared (specify an initial value). Initialization consists of an equal sign followed by a constant expression, as follows: Some examples: Initializing variables correctly is a good programming habit, otherwise sometimes the program will produce unexpected results. Take a look at the following example, using various types of variables: When the above code is compiled and executed, it produces the following results: enum also allows you to define reference type variables, such as class . We will discuss these in later chapters. In this section, we only look at the basic variable types. 1.7.1. C# variable definition #
<data_type> <variable_list>;
data_type must be a valid C# data type, which can be char 、 int 、 float 、 double or other user-defined data types. variable_list can consist of one or more identifier names separated by commas.int i, j, k; char c, ch; float f, salary; double d;
int i = 100;
1.7.2. C# variable initialization #
variable_name = value;
<data_type> <variable_name> = value;
int d = 3, f = 5; /* Initialize d and f. */ byte z = 22; /* Initialize z. */ double pi = 3.14159; /* Declare the approximate value of pi */ char x = 'x'; /* The value of variable x is 'x' */
Example #
namespace VariableDefinition { class Program { static void Main(string[] args) { short a; int b ; double c; /* Actual initialization */ a = 10; b = 20; c = a + b; Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c); Console.ReadLine(); } } }
a = 10, b = 20, c = 30
1.7.3. Accept values from users #
System in the namespace Console class provides a function ReadLine() to receive input from the user and store it in a variable.