Knowledge Management Banner

Knowledge Management Banner

C# Tutotial : Data types : Part 5

There are three datatypes in c#
  • Value types
  • Reference types
  • pointer types

Value Type 

A value type variable can be assigned a value directly. Following are the value types in c#.
  • bool
  • byte
  • char
  • decimal
  • double
  • enum
  • float
  • int
  • long
  • sbyte
  • short
  • struct
  • uint
  • ulong
  • ushort
Value types directly contains data. Copy made of the value that is assigned to another value. This means when a  any value-type instance is created, a single space in memory is allocated.when copy of data is made, it’s dealing directly with its underlying data. Hence, any changes happened to that variable will not affect on original data which is stored in a variable.

e.g.
using System;
class Program
{
    static void Main(string[] args)
    {
        int x = 2;
        int y = x;
        x++;
        Console.WriteLine(y);// it will display 2, x++ won’t affect on y
        Console.Read();
    }
}


Reference Type 
  • The reference types do not contain the actual data stored in a variable, but they contain a reference to the variables
  • Example of built-in reference types are: object, dynamic, and string.
Reference type doesn’t contain data directly, rather it contains reference to data (address of data).The actual data is stored in an area of memory called the heap. Hence, any changes made on this variable will going to affect on data which is stored on that particular reference.When programmer assigns reference variable to another, this doesn’t copy the data. Instead, it creates a second copy of the reference, which refers to the same location of the heap.

e.g.

    class Program
    {
        static void Main(string[] args)
        {
            StringBuilder x = new StringBuilder(“Hello “);
            StringBuilder y = x;
            x.Append(“World”);
            Console.WriteLine(y);//it will display Hello World
            Console.Read();
           
        }
    }

Pointer Type
  • Pointer type variables store the memory address of another type.
  • e.g. int* num;

Reference Type vs Pointer Type

  • Pointer points to a place in memory While a reference points to an object in memory. 
  • A reference however points to a specific object. Objects can be moved around in memory but the reference cannot be invalidated .
  •  References are much safer in this respect than pointers.






No comments

Powered by Blogger.