Tuesday, April 19, 2016

C# Datatypes - Datatype Conversion, Boxing & Unboxing

Since C# is a strongly typed language, each variable used in the program should have a type and the data types are declared when we declare the variable. The C# data types are categorized into three types:
  • Value Types:
    • Predefined – int, char, short
    • User-defined types – Structure, Enumerations
  • Reference Types : 
    • Predefined – Objects, Strings
    • User-defined types – Arrays, Classes, Interfaces
  • Pointer Types
  • The variables which are based on value types they directly contains values. But the reference type variables differ from value types as they contain the reference of the object. The value types are derived implicitly from System.ValueType whereas the reference types cannot derive new type from the value type.
    The value type contains the null value and each value type has the implicit default constructor that initialize the default value of that type. Like
    int a = new int ( ); which is same as int a = 0;
  • Value TypesReference Types
    They are allocated on stack.They are allocated on heap.
    It contains value.It contains the address of the memory location.
    Struct is value type.Classes and Interfaces are reference types.
    Let us have some discussion on Nullable Types and Enumeration Types which are part of value types.
    • Nullable Types – They are the instances of the System.Nullable<T> where T should be a non nullable value type. It represents the correct range of values. The nullable types represent the value type variables which are assigned the null value.
    • Enumerations – It is a set of named integer constants. It is inherited from System.enum
    • Syntax: enum name {list};
      Examples: enum Months {Jan, Feb, Mar, Apr};
      The members can be accessed through dot operator. The keyword enum is used to declare an enumeration a distinct type which consist the set of named constants called enumerator list. They can be defined directly within a namespace so that it can be accessed by all classes in that namespace.

No comments: