C#
  Home arrow C# arrow Type Conversions
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C#

Type Conversions
By: Rajesh V S
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 3 stars3 stars3 stars3 stars3 stars / 7
    2003-05-05

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Type conversions differ slightly in C# as opposed to regular C++. Rajesh has put together an article to demonstrate the different types of conversions possible in the C# language.

    Type conversion is a process of converting one type into another. Using C# type conversion techniques, not only you can convert data types, you can also convert object types. The type conversion in C# can be either implicit conversion or an explicit conversion.

    If one type of data is automatically converted into another type of data, it is known as implicit conversions. There is no data loss due to implicit conversion. But explicit conversion is a forced conversion and there may be a data loss. Type conversions occur mainly when we pass arguments to a function or mixing mode arithmetic etc. 

    Implicit Conversions in C#

    The implicit conversions can occur in a variety of situations like function invoking, cast expressions, assignments etc. The implicit conversions can be further classified into different categories. 

    Implicit Numerical Conversions
     
    The possible implicit numerical conversions in C# are shown below.

    • uint
    • ulong
    • float
    • double
    • decimal
    • ushort
    • short
    • int
    • long
    • sbyte
    • byte
    • char

    The implicit conversions in the direction of arrow are possible with basic data types of C#. Remember that there are no implicit conversions to the char type from any other types. Also there are no implicit or explicit conversions associated with bool type. The examples for implicit numerical conversions are shown below.

    long x;
    int y = 25;
    x = y; //implicit numerical conversion
     

    Implicit Enumeration Conversion

    An implicit enumeration conversion permits the decimal integer literal 0 to be converted to any enum type. 

    Implicit Reference Conversion 

    The possible implicit reference conversions are:

    • From any reference type to object.
    • From any class type D to any class type B, provided D is inherited from B.
    • From any class type A to interface type I, provided A implements I.
    • From any interface type I2 to any other interface type I1, provided I2 inherits I1.
    • From any array type to System.Array.
    • From any array type A with element type a  to an array type B with element type b provided A & B differ only in element type (but the same number of elements) and both a and b are reference types and an implicit reference conversion exists between a & b.
    • From any delegate type to System.Delegate type.
    • From any array type or delegate type to System.ICloneable
    • From null type to any reference type.

    Boxing Conversions

    Boxing is the conversion of any value type to object type. Remember that boxing is an implicit conversion. Boxing a value of value type like int consists of allocating an object instance and copying the value of the value type into that object instance. An example for boxing is shown below. 

    int x = 10;
    object o = x; //Boxing
    if(o is int)
    Console.WriteLine(“o contains int type”);
     

    A boxing conversion making a copy of the value being boxed. But when we convert a reference type to object type, the object continues to reference the same instance. 

    Explicit Conversions in C#

    The explicit conversions are forced conversions in C# by using the casting operator (). There may be a data loss due to explicit conversions. For example when we explicitly convert a double type to an int type as shown below         

    int x = (int) 26.45; //Explicit conversion
    Console.WriteLine(x); // Displays only 26
     

    Explicit Numerical Conversions 

    They are the conversions from a numeric type to another numeric type for which an implicit conversion doesn’t already exist. It is possible to convert any numerical type to any other numerical type explicitly. The explicit numerical conversions can result possibly a data loss or OverflowException to be thrown.  

    Explicit Enumeration Conversions 

    The explicit enumeration conversions are:

    • From sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double or decimal to any enum type.
    • From any enum type to sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double or decimal.
    • From any enum type to any other enum type.

    Explicit Reference Conversions 

    The possible explicit reference conversions are:

    • From object to any reference type.
    • From any class type B to any class type D, provided B is the base class of D
    • From any class type A to any interface type I, provided S is not sealed and do not implement I.
    • From any interface type I to any class type A, provided A is not sealed and implement I.
    • From any interface type I2 to any interface type I1, provided I2 is not derived from I1.
    • From System.Array to any array type.
    • From System.Delegate type to any delegate type.
    • From System.ICloneable to any array or delegate type.

    Because of any reasons, if an explicit reference conversion fails, an InvalidCastException is thrown. 

    Un-boxing Conversions 

    Un-boxing is the conversion of an object type to a value type. The casting operator () is necessary for un-boxing. The example for un-boxing is shown below. 

    int x = 100;
    object o = x; // Boxing
    int I (int) o; // un-boxing

    For an un-boxing conversion to a given value type to succeed at run-time , the value type of the source argument must be reference type to an object that was previously created by boxing a value of the value type. If the source argument is null or a reference type to an incompatible type, an InvalidCastException is thrown. 

    User-Defined Conversions
     
    Whatever we explained till now is the conversions (implicit or explicit) among the basic data types or among same user defined data types. Suppose we have to do conversions between basic data types and user defined data types or between two incompatible user-efined data types. C# provides a facility to define conversion operators inside a class or struct to achieve this. 

    But C# provides only certain user-defined conversions to be defined. In particular it is not possible to redefine an existing implicit or explicit conversion in C#. A class or struct is permitted to declare a conversion function from a source type S to a target type T only if all of the following are true.

    1. Both S & T are different types.
    2. Either S or T is a class or struct type in which the operator declaration takes place.
    3. Neither S nor T is an object type or an interface type.

    T is not a base class of S or S is not a base class of T. The user-defined conversion can either implicit or explicit. The general form of user-defined conversion operator is as follows.

    public static implicit/explicit operator type (arguments)
    {
    }
     

    Where the operator is the required keyword and type is the required return type. Remember that operator function should be public and static and there is no return type. The presence of the keyword explicit makes the conversion as explicit and implicit keyword makes the conversion as implicit. 

    The conversion operator can be defined either inside the class or struct type. Remember that user defined conversions are not allowed to convert from or to interface types. Also note that since explicit or implicit keywords are not part of the method’s signature, it is not possible to declare both explicit and implicit conversion operator with a same source and target type. 

    An example for a user-defined conversion is shown below. 

    // Conversions
    // Author:
    rajeshvs@msn.com
    using System;
    class MyDigit
    {
                private int x;
                public MyDigit ()
                {
                }
               public MyDigit (int i)
                {
                            x = i;
                }
                public void ShowDigit
                {
                            Console.WriteLine("{0}",x);
                }
                public static implicit operator int(MyDigit md)
                {
                            return md.x;
    }
    public static explicit operator MyDigit(int val)
    {
                return new MyDigit(val);
    }
    }
    class MyClient
    {
                public static void Main()
                {
                            MyDigit md1 = new MyDigit1(10);
                            int  x = md1; //Implicit
                            Console.WriteLine(x); //Displays 10
                            int y = 25;
                            MyDigit md2 = (MyDigit)y; //Explicit
                            Console.WriteLine(md2.ShowDigit());
                }
    }

    The above example converts a basic type to a class type and a class type to basic type by using the conversion operator. The conversion operator can be used to convert one class type to another also. An example is shown below.

    // Conversions
    // Author:
    rajeshvs@msn.com
    using System;
    class MyClass1
    {
                public int x;
                public MyClass1(int a)
                {
                            x = a;
                }
                public void Show1()
                {
                            Console.WriteLine(x);
                }
                public static explicit operator MyClass2 (MyClass1 mc1)
                {
                            MyClass2 mc2 = new MyClass2(mc1.x * 10, mc1.x *20);
                            return mc2;
                }
    }
    class MyClass2
    {
                public float x, y;
                public MyClass2(float a, float b)
                {
                            x = a;
                            y = b;
                }
                public void Show2()
                {
                            Console.WriteLine(x);
                            Console.WriteLine(y);
                }
    }
    class MyClient
    {
                public static void Main()
                {
                            MyClass1 mc1 = new MyClass1(100);
                            mc1.Show1();
                            MyClass2 mc2 = (MyClass2)mc1;
                            mc2.Show2();
                }
    }

    If a user-defined conversion can give rise to exceptions or loss of information, then that conversion should be defined as an explicit conversion. In general user defined implicit conversions should be designed to never thrown exceptions and never loss information. Remember that user defined conversions can be either defined inside source class or inside a target class in the case of class-to-class conversions.


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More C# Articles
    More By Rajesh V S

     

    IBM® developerWorks developerWorks - FREE Tools!


    Build Forge Express demo: Enabling software delivery excellence for small and midsized businesses

    This demonstration gives you an overview of IBM® Rational® Build Forge Express Edition, a global offering that provides a framework to automate and execute software processes. Rational Build Forge provides a software assembly line that can support all of your tools, technologies, and platforms so you can achieve a repeatable, reliable, and traceable build and release process.
    FREE! Go There Now!


    NEW! Application Development Tools for the Mainframe Developer

    You probably have thousands of lines of COBOL code loaded with business intelligence and being used to run your business, along with an army of developers maintaining these applications. Learn how to prepare your applications and developers so you can keep that competitive edge and move to a service-oriented architecture with the IBM Rational Enterprise Modernization solutions. Replay is available for 9 months.
    FREE! Go There Now!


    NEW! Cook up Web sites fast with CakePHP, Part 4: Use CakePHP's Session and Request Handler components

    CakePHP is a stable production-ready, rapid-development aid for building Web sites in PHP. This "Cook up Web sites fast with CakePHP" series shows you how to build an online product catalog using CakePHP.
    FREE! Go There Now!


    NEW! Download IBM Rational Developer for System z

    Download a free trial version of IBM Rational Developer for System z, software that can help you deliver core development capabilities; the power of Java Platform, Enterprise Edition (Java EE); and rapid application development support to diverse enterprise application development teams. With comprehensive development tools to help create, deploy and maintain traditional enterprise and composite applications, Rational Developer for System z enables developers with different technical backgrounds to easily participate in important technology projects.
    FREE! Go There Now!


    NEW! IBM Rational ClearCase Innovator's Series

    Learn from the best! Find out how developers use Rational ClearCase to be more flexible, innovative and deliver higher quality code in the Rational ClearCase Power Users eKit. This complimentary eKit provides a collection of materials, like articles, whitepapers, and demos that can help you become a power user of Rational ClearCase.
    FREE! Go There Now!


    NEW! Info 2.0: Harnessing the power of Web 2.0 and Enterprise Mashups

    Listen to this webcast to get an overview of Info 2.0 and a technical demo of how to quickly build an enterprise mashup. IBM's Info 2.0 technology leverages emerging Web 2.0 technologies such as mashups, feeds, AJAX, and JSON in order to simplify assembly of information using feeds and services. Come learn about the technical elements of Info 2.0 including the Feed Generation framework, Mashup Engine, and mashup assembly components. Learn how to pull information from databases, departmental information, and the Web to create mashups critical to your company’s success. We will also discuss best practices to help you get started.
    FREE! Go There Now!


    NEW! Innovate don't duplicate! Asset reuse strategies for success

    Asset Reuse is a key strategy for companies looking to create innovative solutions to solve complex software development problems. Searching for, identifying, updating, using and deploying software assets can be a difficult challenge. Listen to this webcast, to learn about strategies and tools that you can leverage for a successful project, including Rational Asset Manager, Rational Software Architect and WebSphere Service Registry and Repository.
    FREE! Go There Now!


    NEW! Rational Testing eKits

    Discover how Rational tools and best practices for testing can make your job easier. The new Rational Testing eKits provide you with valuable resources – including demos, webcasts, tutorials, and articles – that help you address your specific testing needs across the software lifecycle. Five new eKits are available covering the topics of Requirements and Test Management, Functional Testing, Performance Testing, Code Quality and Embedded Systems, and SOA and Web Services Testing.
    FREE! Go There Now!


    NEW! Trial download: IBM Lotus Forms V3.0

    Get a free trial download of IBM Lotus Forms V3.0 (formerly Workplace Forms), which provides a zero-footprint eForms solution to help you automate and move forms-based business processes off the desktop and onto the Web. With Lotus Forms, you can extend applications beyond the firewall by creating a single electronic form document ready for use in both thick and Web 2.0 thin client format.
    FREE! Go There Now!


    NEW! Webcast: What is new in Viper 2 for developers?

    Viper 2 brings a great value to developer communities including SQL, XML, PHP, Ruby, .NET and Java. You probably already know that DB2 Express-C is free for developers to develop, deploy and distribute. Viper 2 provides a variety of means that help move your application from the development stage to deployment more rapidly. This webcast shows how to best utilize the latest tools available for developing DB2 applications.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    C# ARTICLES

    - Introduction to Objects and Classes in C#, P...
    - Visual C#.NET, Part 1: Introduction to Progr...
    - C# - An Introduction
    - Hotmail Exposed: Access Hotmail using C#
    - Razor Sharp C#
    - Introduction to Objects and Classes in C#
    - Making Your Code CLS Compliant
    - Programming with MySQL and .NET Technologies
    - Socket Programming in C# - Part II
    - Socket Programming in C# - Part I
    - Creational Patterns in C#
    - Type Conversions
    - Creating Custom Delegates and Events in C#
    - Inheritance and Polymorphism
    - Understanding Properties in C#







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek