A variable is a name given to a storage area that is used to store values of various data types. Each variable in C# needs to have a specific type, which determines the size and layout of the variable’s memory.
To perform any operation on variables it is essential to define a variable with a particular data type to specify the type of data that the variable can hold in our application. Let’s see a few basic things about variables:
Programs process data. Typically, They work as follows:
The basic value types provided in C# can be categorized as:
Type | Example |
---|---|
Decimal types | decimal |
Boolean types | true or false values, as assigned |
Integral types | int, char, byte, short, long |
Floating point types | float and double |
Nullable types | Nullable 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.
There are some rules to declare C# Variables:
Before using a variable, you need to declare it using the following syntax:
[Data Type] [Variable Name];
[Data Type] [Variable Name] = Value;
[Access Specifier] [Data Type] [Variable Name] = Value;
In this syntax:
They are some suitable methods to describe the variable names in c# programming language:
int num;
float value;
char _name;
You can also initialize a variable at the time of definition as follows:
int value = 500;
The following table illustrates the most commonly used built-in types:
Type | Meaning | Examples |
---|---|---|
int | Integers | 1, 2, 3 |
float | Single-precision floating-point numbers | 1.1F |
double | Double-precision floating-point numbers | 2.5 |
string | Text strings | “Hi” |
char | Characters | ‘a’, ‘b’,’c’ |
bool | boolean values | true, false |
To assign a value to a variable called initialization, variables can be initialized with an equal sign by the constant expression, variables can also be initialized at their declaration.
Syntax:
[data_type] [variable_name] = value;
Or
variable_name = value;
For example:
int v1=15, v2= 17;
double pi= 3.1416;
char name='dani';
To declare multiple variables, you use multiple statements:
double weight = 60.5;
double height = 1.72;
If variables have the same type, you can declare them in one statement and use a comma (,) to separate two variables like this:
double weight = 61.5,
height = 2.72;
Console.WriteLine($"The weight is {weight}kg and height is {height}m");
The weight is 61.5kg and height is 1.72m
In c#, we can declare and initialize multiple variables of the same data type in a single line by separating with a comma(,
).
Following is the example of defining the multiple variables of the same data type in a single line by separating with a comma(,
) in the c# programming language:
int a, b, c;
float x, y, z = 1.5;
While declaring the multiple variables of the same data type, we can arrange them in multiple lines to make them more readable. The compiler will treat it as a single statement until it encounters a semicolon (;
).
Following is the simple of defining the multiple variables of the same data type in multiple lines in c# programming language.
int a,
b,
c;
float x,y,
z = 1.5;
To output the age
variable to the console, you use the Console.WriteLine
method as follows:
int age = 22;
Console.WriteLine(age);
Output:
22
To embed the age
variable in a string and display it, you use the following statement:
int age = 22;
Console.WriteLine($"The age is {age}");
Output:
The age is 22;
In this statement:
$
symbol.age
) inside the curly braces {}
.When the compiler sees a string with the $
prefix, it’ll replace all the variables in the curly braces with their corresponding values.
The following code outputs 0, since array elements are implicitly assigned to their default values:
static void Main() {
int[] ints = new int[2];
Console.WriteLine (ints[0]); // 0
}
The following code outputs 0, because fields are implicitly assigned a default value:
class Test {
static int x;
static void Main() {
Console.WriteLine (x);
}
}
The code above generates the following result:
0
In c#, once we declare and assign a value to the variable that can be assigned to another variable of the same data type.
Following is the example of assigning a value of one variable to another variable of the same type in c# programming language:
int a = 522;
int b = a;
string name = "test";
string firstname = name;
In c#, it’s mandatory to assign a value to the variable before we use it; otherwise, we will get a compile-time error.
If we try to assign a value of string
data type to an integer
data type or vice versa, as shown below, we will get an error like “cannot implicitly convert type int to string”.
int b = 500;
string name = b;
The following table lists the the default value for the predefined types:
Type | Default value |
---|---|
All reference types | null |
All numeric and enum types | 0 |
char type | '\0' |
bool type | false |
We can get the default value for any type using the default
keyword:
decimal d = default (decimal);
The default value in a custom value type, for example struct
, is the same as the default value for each field.
The following example uses various types of variables:
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 result:
The Console
class in the System
namespace provides a function ReadLine()
for accepting input from the user and store it into a variable.
For example:
int num;
num = Convert.ToInt32(Console.ReadLine());
The function Convert.ToInt32()
converts the data entered by the user to int data type, because Console.ReadLine()
accepts the data in string format.
There are two kinds of expressions in C#:
lvalue
: An expression that is an lvalue may appear as either the left-hand or right-hand side of an assignment.rvalue
: An expression that is an rvalue may appear on the right- but not left-hand side of an assignment.
The following are some valid ways to define the variable names in the c# programming language:
int x;
string _y;
int m20;
float a2b;
char _abc;
The following are some of the Invalid ways of defining the variable names in the c# programming language:
int 5;
int x y;
int double;
float 2abc;
char &abc;
double int;