C#
  Home arrow C# arrow Page 4 - Behind the Scenes Look at C#: Type Convers...
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Mobile Linux 
App Generation ROI 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
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#

Behind the Scenes Look at C#: Type Conversions continued
By: Michael Youssef
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 14
    2005-08-03

    Table of Contents:
  • Behind the Scenes Look at C#: Type Conversions continued
  • Implicit and Explicit Reference-Types Conversion
  • User Defined Type Conversions
  • Explanation and One More Example

  • 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


    Behind the Scenes Look at C#: Type Conversions continued - Explanation and One More Example


    (Page 4 of 4 )

    We have defined three classes in the hierarchy. The Person base class defines two private fields and two public properties. The Customer and the Worker classes both inherit the Person class, override the ToString() method and add one more property. The Worker class adds the property Department (along with the private field) and the Customers class adds the property OrderID along with the private field orderID. The Worker class defines the explicit casting method.

    public static explicit operator Customer(Worker work)
    {
      Customer temp = new Customer();
      temp.FirstName = work.FirstName;
      temp.LastName = work.LastName;
      temp.OrderID = "000000000";
      return temp;
    }

    As you can see, the syntax is very similar to the operator overloading methods; it's public and static, but the new keyword here is the explicit keyword, which states that this is the method that defines the behavior of the explicit conversion that we need to perform using the cast operator. For our example we don't need to define another method for the implicit conversion, because when we cast the worker to the customer type we lose the department data. The cast operator is perfect for this scenario, which we state that we need using the explicit keyword. The return type is Customer and the parameter is of type Worker, so we can write a statement like Customer customer = (Customer)worker. Inside the method we create a new object of type Customer, and we assign the FirstName and the LastName values of the Worker parameter to the Customer instance and set the OrderID to "000000000". The method returns the Customer object after that.

    You can put the user defined type conversion method into the Worker class as we did, or into the Customer class, but not into both of them, because the compiler will not know which one to call. In the Main method we simply instantiate an object of type Worker and set its properties, and another object of type Customer and set its properties. We use the statement customer1 = (Customer)worker1; to explicitly cast the worker1 object to a Customer data type (into the customer1) and print the customer1 object, but this time we will get the values that the cast operation produces (which has the FirstName and the LastName values of the worker1 object).

    You can perform user defined type conversion between your classes and the built-in types as in the following example.

    using System;
    namespace TypeConversion
    {
      class Class1
      {
        static void Main(string[] args)
        {
          Number number = new Number();
          int y = 90;
          number = y; // implicit conversion
          Console.WriteLine(number);

          Number number1 = new Number();
          number1.x = 56.122;

          y = (int)number1; // explicit conversion

          Console.WriteLine(y);
          Console.ReadLine(); 
        }
      }

      class Number
      {
        public double x;

        public override string ToString()
        {
          return Convert.ToString(x);
        }

        public static implicit operator Number(int var)
        {
          Number num = new Number();
          num.x = var;
          return num;
        }

        public static explicit operator int(Number num)
        { 
          checked
          {
            return (int) num.x;
          }
        }
      }
    }

    The result that you will get to the console window is:

    We have used the implicit and explicit type conversions with this example. The class Number simply represents a number;l I have created it as a simple class, but you can put in any other fields and properties you want. The class contains two type conversion methods that perform the implicit and explicit type conversion operations. The implicit method is very easy, it takes as a parameter the int argument and assign it to the x field, and that completes the implicit conversion. The explicit conversion method takes as a parameter the Number instance and returns an int; as you know, the Number instance's x field is of type double, and when it is converted it will lose the digits after the decimal value (as in the example, we got the value 56), which is why we need an explicit cast for this operation.


    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.

       · what happened id i want to convert char type to int typein C# then what have to be...
     

    C# ARTICLES

    - Working with Dates and Times in C#
    - Generics, Dictionaries, and More
    - More About Generics
    - Working with C# Collections
    - Generics
    - C# and XML
    - Pointers and Arrays in C#
    - C# 3.0 Extension Methods
    - Overloading Operators in C#
    - Iterators and Nullable Types
    - Patterns and Iterators in C#
    - C# Exceptions
    - Methods in C#
    - Delegates and Events in C#
    - Advanced C#

     
    Best Practices for Windows Vista Migration Presentation
    Dell and Microsoft recently held a series of face-to-face seminars entitled, &qu....

     
    Creating a Culture for Code Reuse
    If you oversee development teams you know that like it or not proprietary and ex....

     
    Keys to Web Application Acceleration: Advances in Delivery Systems
    Accelerate Web apps by up to 5x. Ensure significantly faster access to the Web a....

     
    Optimizing Application Monitoring
    Tired of finding out from your customers that you're offline? This white paper e....

     
    Solaris to Solaris Migration -- Migrating applications from Sun SPARC to Dell PowerEdge R900
    This comprehensive Migration Guide reviews the approach that Principled Technolo....

     




    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway
    Stay green...Green IT