Variables and Data types in C#

Learn variables and data types in C# programming with super simple explanation with example.

DATA TYPES IN C#

Here are some common data types we use in C# programs. int, float, char, double, Boolean and String.

Data type is a classification of data e.g. int, float, double, char and String etc. by which a programmer and compiler understand how to use them.

For example,

  • numbers 1,2 and 3 etc. is an int data type.
  • 1.00, 12.123 and 25.9 etc. are double type.
  • In double quote “hello” is an String data type etc.

So, this is the way you understand what data type we need to use in the program depending upon the requirement.

Now, let’s say if I ask you what data types of a student name, marks and roll number can be, then easily you can say that the student name should be String type, Marks should be of double data type and roll number can be of int type.

And, a compiler can understand easily, how much space / memory in bytes, it must allocate for String types or double data types and int types to process them.

Also, data types will help you understand which type of variable you want to create to store values.

So for, you have an idea of what is data types in C#programming. Let’s understand what is variables and how to create a variable in C# programs.

VARIABLES IN C#:

We create a variable to store a value. Here is the format to declare a variable.

data type variable name;

You have to write a data type e.g. int , double etc. before variable name, for which type of data you want to store.

Example: int var; // var is a variable of type int. It will store only int values.

More variables examples – If you want to store 72.30, then you can create a double type of variable, if 1234, then int type of variable, “Peter” then String type of variable as shown below

String name = “Peter”; //name is a String data type of variable.
double marks = 72.30; // marks is a double type of variable.
int rollNumber =1234;// rollNumber is of int type of variable.

Lets see a simple program which contains multiple types of variable and has stored the values of respective types.

public class Sample {
 
	public static void Main(String[] args) {
 
		// name variable is of String data type
		String name = "Peter";
 
		// marks variable is of doubl data types
		double marks = 70.56;
 
		// roll number is of int data types.
		int rollNumber = 234567;
 
	}
 
}

In above example, variables of different data types have been created and initialized with respective type of values. Also, you can declare a variable first and then assign a value later as shown below in the C# source code.

public class Sample {
 
	public static void Main(String[] args) {
 
		// Declare variables
		String name;
		double marks;
		int rollNumber;
 
		// Assign values to variables
		name = "Peter";
		marks = 70.56;
		rollNumber = 234567;
 
	}
}

Written By Shilpa Jaroli & Reviewed by Rakesh Singh

Related Posts