C# variable
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 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.
C# variable definition
C# syntax for variable definition
<data_type> <variable_list>;
Here, 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.
Some valid variable definitions are as follows:
int i, j, k;
char c, ch;
float f, salary;
double d;
You can initialize when a variable is defined:
int i = 100;
C# variable initialization
Variables are initialized (assigned) by an equal sign followed by a constant expression. The general form of initialization is:
variable_name = value;
Variables can be initialized when declared (specify an initial value). Initialization consists of an equal sign followed by a constant expression, as follows:
<data_type> <variable_name> = value;
Some examples:
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' */
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:
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();
}
}
}
When the above code is compiled and executed, it produces the following results:
a = 10, b = 20, c = 30
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.