C# Variable

A variable is nothing but a name given to a storage area that the program can manipulate.

In C#, a variable is an identifier used to store and represent data. When declaring a variable, you need to specify the type of the variable and can optionally assign it an initial value.

In C#, each variable has a specific type, which determines the memory size and layout of the variable. Values within that range can be stored in memory, and a series of operations can be performed on the variable.

We have already discussed various data types. The basic value types provided in C# can be roughly divided into the following categories:

TypeExample
Integer Typessbyte, byte, short, ushort, int, uint, long, ulong, and char
Floating-point typefloat, double
Decimal typedecimal
Boolean typetrue or false value, the specified value
Empty string string
empty typeNullable data types

C# allows defining variables of other value types, such asenum, and also allows defining reference type variables, such asclass. These will be discussed in later chapters. In this chapter, we only study the basic variable types.

C# 4.0 introduced the dynamic type, which allows the type of a variable to be inferred at runtime. This is useful in some special cases, but it is usually better to use static types for better performance and compile-time type checking.

dynamic dynamicVariable = "This can be any type";

Variable definitions in C#

The syntax for variable definitions in C#:

<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 shown below:

int i, j, k;
char c, ch;
float f, salary;
double d;

You can initialize at the time of variable definition:

int i = 100;

Variable naming conventions

In C#, variable naming needs to follow some rules:

  • Variable names can contain letters, digits, and underscores.
  • Variable names must begin with a letter or an underscore.
  • Variable names are case-sensitive.
  • Avoid using C# keywords as variable names.
int myVariable = 10;
string _userName = "John";

Variable initialization in C#

Variables are initialized (assigned) by following the equal sign with a constant expression. The general form of initialization is:

variable_name = value;

Variables can be initialized (given an initial value) at the time of declaration. Initialization consists of an equal sign followed by a constant expression, as shown below:

<data_type> <variable_name> = value;

Some examples:

int d = 3, f = 5;    /* 初始化 d 和 f. */
byte z = 22;         /* 初始化 z. */
double pi = 3.14159; /* 声明 pi 的近似值 */
char x = 'x';        /* 变量 x 的值为 'x' */

Initializing variables correctly is a good programming habit; otherwise, the program may sometimes produce unexpected results.

Consider the following example, which uses variables of various types:

Example

using System;
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

Accepting values from the user

SystemIn the namespaceConsoleThe class provides a functionReadLine(), used to receive input from the user and store it in a variable.

For example:

int num;
num = Convert.ToInt32(Console.ReadLine());

FunctionConvert.ToInt32()Convert the user input data to the int data type, becauseConsole.ReadLine()Only data in string format is accepted.

Lvalues and Rvalues in C#

Two types of expressions in C#:

  1. lvalue: An lvalue expression can appear on the left or right side of an assignment statement.

  2. rvalue: An rvalue expression can appear on the right side of an assignment statement, but cannot appear on the left side.

Variables are lvalues, so they can appear on the left side of an assignment statement. Numeric values are rvalues, so they cannot be assigned to and cannot appear on the left side of an assignment statement. The following is a valid statement:

int g = 20;

The following is an invalid statement that will produce a compile-time error:

10 = 20;
other extensions