DataType in C#

C# is strongly typed language; therefore every variable, constant, literal must have a declared type. C# provides a wide range of built-in data types, which makes C# more suitable for various types of application.

All operations in a program are checked for type compatibility at compile time and illegal operations will not be compiled. This type checking ensures the reliability of code and helps to minimize errors.
DataType in C#

Data types in C# are categorized into value types and reference types. Both value types and reference types are derived from ‘System.Object’ class.

The following diagram shows the relation between these data types:C# DataType & Variable

  1. Value Type

The value type variables contain actual data. They are also known as a simple type or primitive type. The value type stores its data in memory allocated on the stack.

When a variable goes out of scope the memory allocated by value type on the stack is reclaimed. Because of portability requirements, C# strictly specifies a range and behavior of each value type. Value types are derived from class ‘System.ValueType’.

The following table lists available value types in C#:

 

Type Represents Size Range
bool Boolean 8 bit True/false
byte Unsigned Integer 8bit 0 to 255
sbyte Signed Integer 8 bit -128 to 127
int Signed Integer 32 bit -2,147,483,648 to 2,147,483,647
short Signed Integer 16 bit -32,768 to 32,767
uint Unsigned Integer 32 bit 0 to 4,294,967,295
ushort Unsigned Integer 16 bit 0 to 65,535
long Signed Integer 64 bit -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
ulong Unsigned Integer 64 bit 0 to 18,446,744,073,709,551,615
char Single Unicode character 16 bit Unicode symbols used in text
double Double precision floating point 64 bit -1.79769313486232e308 to 1.79769313486232e308
decimal Precise decimal values with 29 significant digit 128 bit ±1.0 × 10e−28 to ±7.9 × 10e28
float Single precision floating point type 32 bit -3.402823e38 to 3.402823e38

 

C# language provides sizeof() method to get the size of the data type. It takes data type as argument and returns size of that data type in bytes. Following program demonstrates the use of sizeof() method.

using System;
namespace TypeSize
    {
      class Program
       {
        static void Main(string[] args)
          {
           Console.WriteLine("The size of int data type is {0}",sizeof(int));
           Console.WriteLine("The size of double data type is {0}", sizeof(double));
           Console.ReadLine();
           }
         }
       }

 

The output of above program is:

The size of int data type is 4
The size of double data type is 8

 

2. Reference Type

The reference type variables do not contain actual data instead they contains the pointer to the another memory location where actual data is stored. Variables of reference types are stored on heap memory. The memory of reference type reclaimed when garbage collection system determines it is no longer needed. As reference types stores the memory address of data, more than one variable can refer to same data. Hence if data changes it reflects in all variables.

The following data types are built-in reference types:

  • Object: 

The type object is an alias for ‘System.Object’ class. An object class is root class in .Net framework and all value types and reference types are derived from Object class. Object type variable can hold the value of any other data type.

The following program shows how object can hold any data type:

using System;
namespace ObjectType
{
  class Program
  {
     static void Main(string[] args)
     {
        object obj;
        obj = 10; //Stores integer value
        Console.WriteLine(obj.GetType());
        obj = "C# Programming";   //Stores string value
        Console.WriteLine(obj.GetType());
        Console.ReadLine();
     }
  }
}

The output of above program is:

System.Int32
System.String

 

  • Dynamic:

The variables of dynamic type can hold any type of data just like object type. The only difference between dynamic type and object type is that in the case of object type variable type checking is done at compile time and in the case of dynamic the type checking is done at runtime.

 

using System;
namespace DynamicType
{
     class Program
    {
         static void Main(string[] args)
         {
              dynamic d;
              d = 20;//Stores integer value
              Console.WriteLine(d.GetType());
              d = "C# Programming";//Stores string value
              Console.WriteLine(d.GetType());
              Console.ReadLine();
        }
    }
}

 

Recommended Post   C# OOPS

The output of above program is:

System.Int32
System.String
  • String:

The string type variable stores the sequence of zero or more Unicode characters. The string keyword is an alias for ‘String’ class in .Net framework. String in C# is immutable that means when we make any changes in the existing string it does not change current object instead it create a new object in and stored that reference in the variable. The value of string variables are assigned two ways; in a regular way (double quoted) and verbatim string (@quoted) as below

string str=”This is C# programming”;

Or

string str=@”This is C# programming”;

The difference between these two is that regular string process the escape character sequence (like \n, \t etc) but the verbatim string does not process escape sequence instead it print that sequence as it is.

If you want escape sequence to be a part of string value in the regular string then use the backslash. The following program demonstrates the difference between regular string and verbatim string.

using System;
namespace StringDemo
{
      class Program
     {
          static void Main(string[] args)
         {
              // Regular string
              string S1 = "C# is \nprogramming language.";
           // Regular string with escape sequence as part of string
              string S2 = "C# is \\nprogramming language.";
          // Verbatim string
              string S3 = @"C# is \n programming language.";
              Console.WriteLine(S1);
              Console.WriteLine(S2);
              Console.WriteLine(S3);
              Console.ReadLine();
         }
     }
}

The output of above program is:

C# is
programming language.
C# is \n programming language.
C# is \n programming language.

Another difference between regular string and the verbatim string is that regular string literals (or constants) accept only single line string. But verbatim string accepts multiline string also.

string str=”C# is very powerful language provided
 by Microsoft.”// It will give compile time error

string str=@”C# is very powerful language
provided by Microsoft.” //It will work.

All classes, interfaces, and delegates are user defined reference types in C#.

Variables:

The variable is identifier name given to the memory location where data can be stored during execution of the program. The data stored in the variable may change many times during execution. Every variable in C# must have a specific data type. The variable can store the only value of data type which is declared in a variable declaration.

  • Declaring variables:

The syntax for declaring variable is as below

<TYPE> <variable_name>;

In above syntax, type is the data type of variable and variable_name is name. In .Net environment data types are checked at compile time so it is necessary to declare all variables before using them in the program. From above syntax, we declare integer variable as below

int a;

One can also declare multiple variables of the same type in one statement as below

int a,b,c;
  • Initializing variables:

Once variables are declared we can assign values to these variables and do some operation on it. Before performing the operation on variables, they must be assigned with some values. The syntax for assigning value to variable is as below

<variable_name>=value;

Where variable_name is declared variable and value is the specific value that is assigned to the variable. For example

int a;//Declaration
a=2;// Initialization

One can also declare and initialize a variable in single statement as

int a=2;

We can also initialize multiple variables in single statement as

int a=1, b=2, c=3;

Following program demonstrates declaration and initialization of variables:

using System;
namespace VariableDemo
{
     class Program
     {
         static void Main(string[] args)
         {
              int a;
              a = 10; //Initialize variable a
              int b = 30; //Declaration and initialization in one statement
            // Declaration and initialization of multiple variables in one statement
              int c = 5, d = 6;
              Console.WriteLine("The value of varibale a is {0}", a);
              Console.WriteLine("The value of varibale b is {0}", b);
              Console.WriteLine("The value of varibale c is {0}", c);
              Console.WriteLine("The value of varibale d is {0}", d);
              Console.ReadLine();
         }
   }
}

The output of above program is:

The value of varibale a is 10
The value of varibale b is 30
The value of varibale c is 5
The value of varibale d is 6

C# also allows dynamic initialization of variables at the time of variable declaration. In dynamic initialization, we can initialize the variable with the value return by some expression. The expression must return the value of type compatible with variable type. Let’s see dynamic initialization with the help of example

using System;
namespace DynamicInitialization
{
      class Program
     {
          static void Main(string[] args)
         {
             int a = 5;
             int b = 3;
             int c = a + b; //Dynamic initailization
             Console.WriteLine("The value of variable c is {0}", c);
             Console.ReadLine();
         }
      }
}

The output of above program is:

The value of variable c is 8
  • Scope and Lifetime of variables:

Every declared variable in C# has scope and lifetime. The scope defines the region in the program where the variables are accessible. The scope of the variable is limited to the block in which it is declared. The block starts with opening curly brace and ends with closing curly brace. The scope also defines the lifetime of the variable. In the case of nested code blocks, the variables declared in the inner code block is accessible in all inner blocks but the variables declared in an inner block are not accessible outside of that inner block. Thus scopes protect unauthorized access to the variables.

using System;
namespace VariableScopes
{
    class Program
    {
         static void Main(string[] args)
         {
               int x = 20; // x is accessible to all inner block in main method
              {
                   int y = 10; // y is accessible in inner block
                   Console.WriteLine("The value of x is {0}",x);
                   Console.WriteLine("The value of y is {0}", y);
              }
              Console.WriteLine("The value of x is {0}", x);
             //Console.WriteLine("The value of y is {0}", y); This will gives error
             Console.ReadLine();
      }
   }
}

The output of program is

The value of x is 20
The value of y is 10
The value of x is 20

One point to remember is that variables are declared at any point, but they can be declared before using it. This means if you create variable at the end of the scope they are useless.

The lifetime of the variable is only to the block in which it is declared. The variables are destroyed from memory when control goes out of the scope. A variable declared inside a block lose its value when the block is left.

One more thing is that unlike C/C++ languages C# doesn’t allow the variable in the inner block with the same name as in outer block. But you can use same in two or more blocks if they are not nested in each other.

Let’s see below  example:

using System;
namespace VariableNames
{
    class Program
   {
       static void Main(string[] args)
      {
          int value;// Outer block variable
         {
            //int value = 10;   // Variable with name value not allowed in inner block
            int value1=3;
             Console.WriteLine("The value of variable value1 is {0}",value1);
         }
     {
          //int value = 10;   // Variable with name value not allowed in inner block
          int value1=5;
         Console.WriteLine("The value of variable value1 is {0}", value1);
     }
     Console.ReadLine();
     }
   }
}

 

Recommended Post   C# Tutorial

The output of program is

The value of variable value1 is 3
The value of variable value1 is 5

 

 

 

 

SHARE
Previous articleWhat is Domain?
Next articleC# Type Conversion

LEAVE A REPLY

Please enter your comment!
Please enter your name here