C Sharp/Type Conversion

From Meshplex

Jump to: navigation, search
Image:Csharp_programming.gif

Main Home

Basics
C# Tutorial Home
C# - Introduction to Visual Studio IDE
Introduction to C#
C# - Overview
C# - Statements
C# - Data Types
C# - Variables
C# - Operators
C# - Flow Control
C# - Variables II

C# - Functions and Methods
C# - Classes and Objects I
C# - Enumerations
C# - Dates and Times
C# - Random Numbers

Advanced
C# - Inheritance
C# - Polymorphism
C# - Garbage Collection
C# - Operator Overloading
C# - Encapsulation
C# - Properties
C# - Indexers
C# - Exceptions
C# - GUI
C# - Delegates
C# - Events
C# - Components
C# - Multithreading
C# - Regular Expressions
C# - Graphics and Multimedia
C# - Files and Streams
C# - XML
C# - Database, SQL and ADO.NET
C# - ASP.NET Web Forms and Web Controls
C# - Web Services
C# - Network Programming
C# - Datastructures and Collections
C# - Enumerations and Iterators
C# - .NET Assemblies
C# - CLR
C# - Visual Studio Debugger
C# - Namespaces
C# - Generics
C# - MS Intermediate Language
C# - Deploying Windows Application


I may be necessary to convert one type to another. There are two types of type conversion implicit and explicit.



  • Implicit: Automatic compiler conversion where data loss is not an issue.
  • Explicit: A conversin where data loss may happen and is recommended that the programmer writes additional processing


A common rule of thumb is that it is much easier to convert up then it is to convert down. For example, conversion from int to long is an easy operation, but converting the other way around is not so easy. Remember the long data type is a bigger type then the int data type is. To prevent data loss just remember to convert from small to large.


There may be situations where you cannot get around from converting a large data type to small. This where explicit conversion comes into play.


[edit] Csharp Implicit Conversion

using System;
 
class Program
{
    static void Main(string[] args)
    {
        int x = 2;
        double y = 12.2;
        double z;
        z = x + y;     //x is automatically converted into a double
        Console.WriteLine(z);
        Console.Read();
    }
}

Output

14.2

This is an example of csharp implicit conversion. The compiler implicitly converts x to a double. Data loss is not an issue with this operation.

[edit] Csharp Explicit Conversion

  1. using System;
  2.  
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. double x = 2.1;
  8. int y = 12;
  9.  
  10. int z = (int)x + y; //Explicit conversion from double to int
  11.  
  12. Console.WriteLine(z);
  13. Console.Read();
  14. }
  15. }
  • Line 10: (data type to convert to)variable which is (int)x


x was initialized to 2.1 but was converted to an int so for Line 10 x equaled 2.