Variables and Data types in C#

(Last Updated On: January 9, 2019)

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.

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.

 

 

Written By Shilpa Jaroli & Reviewed by Rakesh Singh