C# Datatypes - Datatype Conversion, Boxing & Unboxing

    1 Votes

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;

 

Let us look at the differences between both the data types:

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.

Pre-defined value types

Some of the pre-defined value types in C# are:

C# Type.Net Framework TypeSignedBytes
sbyte System.sbyte Yes 1
short System.Int16 Yes 2
int System.Int32 Yes 4
long System.Int64(L or l) Yes 8
byte System.Byte No 1
ushort System.Uint16 No 2
uint System.Uint32 No 4
ulong System.Uint64 No 8
float System.Single(F or f) Yes 4
double System.Double(D or d) Yes 8
decimal System.Decimal(M or m) Yes 12
char System.Char N/A 2
bool System.Boolean N/A 1

Type Casting

The type casting is the type conversion of one data type into another data type. In C# there are two types of type casting:

Implicit Conversion

In this conversion no special syntax is required because this conversion is type safe and no data will be lost. For example, Convert small to large integer types, converting from derived class to base class. Let us have a look on example

using System;
class A
{
public int a;
public static implicit operator B (A m)
{
B w = new B ( );
w.a = m.a * 2;
return w;
}
}
class B
{
public int a;
public static implicit operator A (B w)
{
A m = new A ( );
m.a = w.a / 2;
return m;
}
}
class Program
{
static void Main ( )
{
A m = new A ( );
m.a = 10;
Console.WriteLine (m.a);
// Implicit conversion from A to B.
B w = m;
Console.WriteLine (w.a);
// Implicit conversion from B to A.
A m2 = w;
Console.WriteLine (m2.a);
}
}

Output:
10
20
10

Explicit Conversion

In this conversion it requires cast operator. The casting is required when the information is lost or the conversion or the conversion is not succeeded. It converts integer values into higher or lower range, converting base class instance to derived class. Let us have a look on example:

using System;
namespace ConsoleApplication1
{
class Explicit
{
static void Main (string [] args)
{
double d = 10.50;
int i;

// casting double to int.
i = (int) d;
Console.WriteLine (i);
Console.ReadKey ();
}
}
}

Output : 10

Type Conversion:

The conversion of one data type into another data type is the Type Conversion or Type Casting. Let us look at some examples:

int to Boolean Datatype Conversion

using System;
namespace TypeConversionApplication
{
class ExplicitConversion
{
static void Main(string[] args)
{
int a = 0;
bool b = Convert.ToBoolean(a);
Console.WriteLine(b);
Console.ReadKey();
}
}
}

Output : False

int to Char Datatype Conversion

using System;
namespace TypeConversionApplication
{
class ExplicitConversion
{
static void Main(string[] args)
{
int a = 66;
char b = Convert.ToChar(a);
Console.WriteLine(b);
Console.ReadKey();
}
}
}

Output :DB

int to Decimal Datatype Conversion

using System;
namespace TypeConversionApplication
{
class ExplicitConversion
{
static void Main(string[] args)
{
int a = 20;
decimal b = Convert.ToDecimal(a);
Console.WriteLine(b);
Console.ReadKey();
}
}
}

Output : 20

int to Double Datatype Conversion

using System;
namespace TypeConversionApplication
{
class ExplicitConversion
{
static void Main(string[] args)
{
int a = 30;
double b = Convert.ToDouble(a);
Console.WriteLine(b);
Console.ReadKey();
}
}
}

Output : 30

int to Float Datatype Conversion

using System;
namespace TypeConversionApplication
{
class ExplicitConversion
{
static void Main(string[] args)
{
int a = 40;
float b = Convert.ToSingle(a);
Console.WriteLine(b);
Console.ReadKey();
}
}
}

Output : 40

int to String Datatype Conversion

using System;
namespace TypeConversionApplication
{
class ExplicitConversion
{
static void Main(string[] args)
{
int a = 66;
string b = Convert.ToString(a);
Console.WriteLine(b);
Console.ReadKey();
}  
}
}

Output : 66

Decimal to int Datatype Conversion

using System;
namespace TypeConversionApplication
{
class ExplicitConversion
{
static void Main(string[] args)
{
decimal a = 10.0M;
int b = Convert.ToInt32(a);
Console.WriteLine(b);
Console.ReadKey();
}
}
}

Output : 10

Decimal to Float Datatype Conversion

using System;
namespace TypeConversionApplication
{
class ExplicitConversion
{
static void Main(string[] args)
{
decimal a = 20.0M;
float b = Convert.ToSingle(a);
Console.WriteLine(b);
Console.ReadKey();
}
}
}

Output : 20

Float to int Datatype Conversion

using System;
namespace TypeConversionApplication
{
class ExplicitConversion
{
static void Main(string[] args)
{
float a = 70.0f;
int b = Convert.ToInt32(a);
Console.WriteLine(b);
Console.ReadKey();
}
}
}

Output : 70

String to int Datatype Conversion

using System;
namespace TypeConversionApplication
{
class ExplicitConversion
{
static void Main(string[] args)
{
string a = "97";
int b = Convert.ToInt32(a);
Console.WriteLine(b);
Console.ReadKey();
}
}
}

Output : 97

Boxing and Unboxing

Boxing is a process of converting a value type to the object type or to any other interface type which is implemented by this value type. When CLR boxes a value type it wraps the value inside a System.Object and stores it on the managed heap. Boxing is done implicitly. It is used to store the value types in the garbage collected heap. It allocates an object instance on the heap and copies the value into the new object. For example:

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace ConsoleApplication1  
{  
    class boxing  
    {  
        public static int a
        {  
            get;  
            set;  
        }  
        public static void Main ( )  
        {   
            int i = 10;  
            object j = i;   //statement for boxing
  
           Console.WriteLine ("Enter the value: ", a);  
            a= Convert.ToInt32 (Console.ReadLine ( ));  
  
            if (i <= a)  
            {  
                i += a;  
                Console.WriteLine ("\n The sum is: ", i);  
            }  
            else  
            {  
                Console.WriteLine ("\nWrong answer…");  
            }  
            Console.ReadLine ( );  
        }    
    }    

The unboxing is an explicit conversion from the type object to a value or from an interface type to a value that implements interfaces. The unboxing consists of:

  • Checking the object instance to make sure that it is a boxed value of the given value type.
  • Copy the value from the instance variable into the value type variable.

Let us have a look on the example:

using System;
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace ConsoleApplication1  
{  
    class unboxing  
    {  
        public static int a
        {  
            get;  
            set;  
        }  
        public static void Main ( )  
        {   
            int i = 10;  
            object j = i;  
   i = (int) j;       //statement for unboxing Console.WriteLine ("Enter the value: ", a);  
            a= Convert.ToInt32 (Console.ReadLine ( ));  
  
            if (i <= a)  
            {  
                i += a;  
                Console.WriteLine ("\n The sum is: ", i);  
            }  
            else  
            {  
                Console.WriteLine ("\nWrong answer…");  
            }  
            Console.ReadLine ( );  
        }    
    }    
}
Planning to do an MBA?
A quick all-in-one MBA entry manual for MBA Aspirants. Book covers
  • Possible MBA Tests & Exam Preparation
  • Tips to choose right MBA Program
  • Essay, Resume & Letter of Recommendation
  • MBA Interview Preparation
  • MBA Financial Planning
Price - 6.99$
 

Popular Videos

How to speak to people

How to speak so that people want to listen.

Got a tip or Question?
Let us know

Related Articles

C# Overview & Evolution of C# Language
Introduction of .NET Framework
C# Metadata, Metadata Tables and Benefits
C# - Common Language Intermediate (CIL)
C# - Class and Objects
C# Assembly - How to create and share assembly
C# Garbage Collection
C# Indexers
C# Exception Handling - User-Defied Exceptions
C# Inheritance - Single, Hierarchical, Multilevel & Multiple Inheritance
C# Polymorphism - Static and Dynamic polymorphism
C# Abstract Classes
C# Structures
C# Delegates and Events
C# Collections
C# XML Read and Write
C# Windows Presentation Foundation (WPF)
Language Integrated Query (LINQ)