Menu Close

C# Variables

In this article we will learn about csharp variables, A variable is nothing but a name given to a storage area that our programs can manipulate. Please read our previous article WPF Metro Window with MahApps.Metro.

For more details about C# visit this link.

About C# Variables

A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C# has a specific type, which determines the size and layout of the variable’s memory the range of values that can be stored within that memory and the set of operations that can be applied to the variable.

Csharp .NET

The basic value types provided in C# can be categorized as −

Integral typessbyte, byte, short, ushort, int, uint, long, ulong, and char
Floating point typesfloat and double
Decimal typesdecimal
Boolean typestrue or false values, as assigned
Nullable typesNullable data types

C# also allows defining other value types of variable such as enum and reference types of variables such as class, which we will cover in subsequent chapters.

Variable Declaration

Syntax for variable definition in C# is −

<data_type> <variable_list>;

Here, data_type must be a valid C# data type including char, int, float, double, or any user-defined data type, and variable_list may consist of one or more identifier names separated by commas.

The example of declaring variable is given below:

int i, j;  
double d;      
float f;      
char ch;    

Here, i, j, d, f, ch are variables and int, double, float, char are data types.We can also provide values while declaring the variables as given below:

int i=2,j=4;  //declaring 2 variable of integer type      
float f=40.2;      
char ch='B'; 

Rules for defining variables

A variable can have alphabets, digits and underscore.

A variable name can start with alphabet and underscore only. It can’t start with digit.

No white space is allowed within variable name.

A variable name must not be any reserved word or keyword e.g. char, float etc.

Valid Variables

int x;      
int _x;      
int k20; 

Invalid Variables

int 4;      
int x y;      
int double; 

Notice Title

The variable is a name given to a data value.

A variable holds the value of specific data type e.g string, int, float etc.

A variable can be declared and initialized in separate statements and also in the single statement.

The value of a variable can be changed at any time thought out the program as long as it is accessible.

Multiple variables can be defined separated by comma (,) in a single or multiple line till semicolon(;).

A value must be assigned to a variable before using it otherwise it will give compile time error.


Hope It will clear about the C# Variables.

Leave a Reply

Your email address will not be published. Required fields are marked *