C# DataTypes and Variables

C# DataTypes and Variables

What is a Variable?

Variables are the programming equivalents of memory areas in which we can store different types of data. In almost all programming languages, variables are defined before they are used. When the compiler discovers the definition line, it allocates an appropriate amount of space in the memory to the object's property. Value (data) of a variable can change depending on the program.

 

What is Runtime?

The running process of the program is called runtime. When the program is closed, the runtime ends and the contents of the variables are deleted. So we can store information in variables only during runtime.

 

What is a DataType?

There are different types of data need to be stored like integers, texts or 0/1 datas. Allocating appropriate memory areas for these different data types is important for performance management. Therefore there are variable types that store different types of data. All data types have a different limit to store data, and no data type have capacity to store unlimit amount of data.

 

Primitive DataTypes in C#

primitive datatypes in c#

Note: String is not a primitive datatype (it is a class), that's why first letter of String is capitalized. But It can also be written as string.

 

Creating a New Variable

Example 1: Define a new variable names a and assign value of 5.

int a = 5;

 

Example 2: Print out the value of the integer a.

int a = 5;
Console.WriteLine(a);
//output: 5

 

Example 3: Define two integers with values and calculate sum of these values as a third variable called sum.

int a = 5;
int b = 8;
int sum = a + b;
Console.WriteLine(sum);
//13

 

Example 4: Define two double variables with floating values and calculate sum of these values as a third variable called sum.

double a = 2.85;
double b = 11.6548;
double sum = a + b;
Console.WriteLine(sum);
//14.5048

 

Example 5: Declare two variables in one line and assign values later.

int a, b;
a = 10;
b = 30;
double sum = a + b;

 

Example 6: Declare two float variables and find their multiplication as a third float variable.

float a = 1.8f;
float b = 15.3f;
float sum = a + b;
Console.WriteLine(sum);
//17.1