Type Of Variables In C# In Detail

10:02 Add Comment
Variables are most important part of programming. They hold the data that are needed by the user. Initializing, assigning and transferring values or data of variable. These basic things a programmer must know. They act like key in programming for generating data as output. So we are going to see some commonly used type of variables in c#. 



We already know all data type have specific type and size associated with it. This will help in determining the operations and their impact on variables. Since C# is strongly type language so while transferring data from one to another be cautious about their type and size for error free execution of your program.

There are 5 different datatype that C# provides:
Integer Type: Integer type can used with short, ushort, int, uint, long, ulong. It will store numeric data type without precision.
Floating Point Type: It will store numeric data with precision. There are 2 type provided for this: float and double.
Decimal Type: Store large decimal numeric data.
Boolean Type: only store true or false as value.
Nullable Type: Store Nullable  data type.

Before moving ahead, this question always confused beginners or students as well. The following question comes to the exam or most likely question asked in Viva of Engineering or any programming language.

What is difference between defining and initializing the variable?

Here is the brief answer:

Defining Variable:

Defining variable just declare variable but do not assign any value to it. For that you must know how to define it.

Syntax for C#:
<data type> <variable name / variable list>;

Here data type can be anything from above data type. Here are some example.
 int i,j,k;
char ch,ab;
float f,sal;
double d;

This is called the defining variable. Here we have just defined variable with their type but still they do not have any value assign to them.

Initializing variable:

After defining them we can initialize the variable. Assigning the value to the variable already defined is called initializing them. 

So it will be:
<Variable name>=value;

We can also do defining and initializing at the same step like this:
int a=10;
string name=”Dharmesh”;
float f=3.14,sal=20000;
char cha=’a’,ab=’c’;

Let’s see one full program where we first define variable then initialize them.

using System;
namespace VariableDefAndInit
{
   class varibales
   {
      static void Main(string[] args)
      {
         byte x;
         int y ;
         float z;

         /* actual initialization */
         x = 100;
         y = 200;
         z = x + y;
         Console.WriteLine("Value of X = "+x);
         Console.WriteLine("\nValue of Y = "+y);
         Console.WriteLine("\nValue of Z = "+z);
         Console.WriteLine("\nValue of X = {0},  Y= {1}, Z = {2}", x, y, z);
         Console.ReadLine();
      }
   }
}
The output for the same is:

Executing the program....
Value of X = 100
Value of Y = 200
Value of Z = 300
Value of X = 100,  Y= 200, Z = 300
This is program is showing hardcode values that are predefined in program. What If you want accept value from user. In real word application there is lot of user interventions. So for that here is one method that accepts data from user. It is method from Console Class and can be accessed by: Console.ReadLine();

Here is an example that accepts number from user and assigns it to variable:
using System;
namespace VariableDefAndInit
{
   class varibales
   {
      static void Main(string[] args)
      {
         int x;
         int y ;
         int z;

         x =Convert.ToInt32(Console.ReadLine());
         y =Convert.ToInt32(Console.ReadLine());
         z =Convert.ToInt32(Console.ReadLine());
         Console.WriteLine("Value of X = "+x);
         Console.WriteLine("\nValue of Y = "+y);
         Console.WriteLine("\nValue of Z = "+z);
         Console.ReadLine();
      }
   }
}
Here we have to user Convert value specifically to int because Cosole.ReadLine() accept data in string format. Hence while assigning to variable we need to convert that into specifically data type or you will get an error.

Other types of variables are called Constant:
As the name suggest their value always remains the constant. Let’s see more about them:

Character constants:
They are also called as character literals. Character are quoted into single quote but there are some special character called escape sequence.  They have special meaning assign to them. All of them start with backslash character “\ ”.
Here is some normally used character constant called Escape sequence:


Escape sequence
Meaning
\a
Alert or bell
\t
Horizontal Tab
\v
Vertical tab
\n
Newline character
\r
Carriage return
\b
Backspace
\”
Print Double quotes in output
\\
Print \ in output
\?
Print ? in output
\’
Print single quote in output

Here is code example for the same:
using System;
namespace CharConstant
{
   class EsacpeSquences
   {
      static void Main(string[] args)
      {
         Console.WriteLine("This is effect of tab\t this is carraige return \rthis is beep \a \nthis is newline character\n");
         Console.ReadLine();
      }
   }
}
Output for the same is:
This is effect of tab     this is carriage return
this is beep
this is newline character
 String Literals:
String literals are same as character literals but they are in string format. They can also be used with character literals. Like we have used in above example. Here all statements like

 “This is effect of tab this is carriage return this is beep this is newline character”

These are all sting literals that are separated by space. You have also seen how they are work with escape sequences.

Defining Constants:
In programming there might be situation comes when we need to make some variable contestant. That means value of that variable always remains the same. They must define an initialize at the same time.

You need to use const keyword in c# for defining any variable as constant.
Syntax:
const <datatype> <variable name>=value;

Got confused let’s take an example:
using System;
namespace DemoConstants
{
    class ConstProgram
    {
        static void Main(string[] args)
        {
            const double pi = 3.14;   //Constant defined
           
            double r;

            Console.WriteLine("Enter Radius: ");
            r = Convert.ToDouble(Console.ReadLine());
            double areaCircle = pi * r * r;
            Console.WriteLine("The area of Circle with Radius: {0} having Area: {1}", r, areaCircle);
            Console.ReadLine();
        }
    }
}
When above code get executed following is the output:

(I am taking here radius value as 6)
Enter Radius:
6
Radius: 6, Area: 113.09724 

SO here we have seen all type of variables in c# and how to deal with them. In next chapter we are going to see decision statement and loop various examples.

C# Data Type In Detail

12:37 Add Comment
Every language has data type to work with different values. C# is strongly type language. Now what does this term means? Well strongly type means which data you have assign to the variable it will not store other data type in it. Example:

int a=10;
byte=a;


The above statement will give you an error. Since int store the data in decimal format have 4 byte and bye store numbers up to 0 to 255. So it will not automatically convert an int to byte. This is called implicit type conversion .While you can do reverse. On the other hand we have sometime tell compiler explicitly to convert object type to value type. This is called explicit type conversion. Let me explain with you laymen example:

Consider int as 2 liter bottle and byte as 1 liter bottle. 2 liter bottle can handle 1 liter water. While you reverse is not true that is 1 little bottle cannot handle 2 liter water. It will overflow. The same case with int and byte. Int (Integer) is 2 liter bottle and byte is 1 liter.

The variables in C# are categorized under 3 Heads:


  1. Value Type
  2. Reference Type
  3. Pointer Type
Value Type:

Value type is derived from System class: System.VlaueType; these variables can assign the values directly i.e. variable directly contain data. Some example of such type are floating point number, integer, Char, double, Boolean etc. Once they are declared then memory is allocated directly. Here is all details that you need to know about.


Type
Representation and Memory
Example
bool
Boolean Value
Bool flag=true;
byte
8 bit unsigned integer (0-255 only)
Byte b=10;                
char
16 Bit Unicode character
char latter=’a’;
int
32 bit sign integer type
int a=25000;
float
32-bit single-precision floating point type
float f=12.16;
double
64-bit double-precision floating point type
double d=12.154780;
long
64-bit signed integer type
Long int =150000;
sbyte
8-bit signed integer type(-128-127)
sbyte a=25;
short
16-bit signed integer type
short int=2500;

You can check the size of every data type by using size of method. This method returns size of datatype. Here is an example code:

using System;
namespace DataTypeSize{
   class CheckSizeOf
   {
      static void Main(string[] args)
      {
         Console.WriteLine("Size of int: {0}", sizeof(int));
         Console.ReadLine();
      }
   }
}
Here you can use float double or any other data type specified above. And Output will provide you storage size for datatype in byte.

Reference type:
Reference does not store any value but they store the reference for the variable. In short they store references of memory location of variable. If data at that location change by any variable then it will automatically get reflected in reference variable. Following are built in reference types:
  • Object
  • Dynamic 
  • String
Object:
Object is main base class for all the data type classes in C#. Alice for object class is System.Object. It can store all type of data in it. Befre assigning the value it need to get converted. Example:
using System;
namespace DataTypeConversion
{
   class TypeConversion
   {
      static void Main(string[] args)
      {
         Object o=100;// Here int is assign to Object instance o.
         Console.WriteLine(0);
      }
   }
}

In above example object type is storing data of integer type. This is automatically getting done. Since object is ultimate class for all data type. While doing reverse you need to do explicate type conversion. This is call as boxing. Example: 

using System;
namespace DataTypeConversion
{
   class TypeConversion
   {
      static void Main(string[] args)
      {
         object o=100;
         int a=Convert.ToInt32(o);
         Console.WriteLine(a);
      }
   }
}
Here we have used here Convert.ToInt32() method that take one argument for converting data type to Integer format. This called unboxing.

String Type:
String type is used to store string or can say alphanumeric character. String is alias for System.String; String type has also derived from Object type.
Here is an example:

String s="Hello How are you?";

Pointer Type:
Pointer type variables store the memory address of another type. Pointers in C# have the same capabilities as the pointers in C or C++.
Example :

Char* cprt;
Int* ap;

There are some other data types also available in C# but like class interface structure delegates that we will discuss in separate section all together. So we have seen almost all normally used data types. In Next chapter we will see further.

Here we have seen Value type, reference type and pointer type in details. Also we have seen their usage for the same. Stay tuned for more.