DotNetBlog der DotNet-Blog Alles rund um Microsoft .NET – von  Sascha H. Baumann

MCTS Examen 70-536 – Converting Types

1 Star2 Stars3 Stars4 Stars5 Stars (Noch nicht bewertet. Seien Sie der/die Erste !)
Loading ... Loading ...

Hello everyone!

Today I learn about Type-Conversion and will share my notes with you. Have fun !

General

  • C# allows widening conversion (destination type can accommodate all possible values) but prohibits narrowing conversion (possible loss of precision).
  • Methods to Convert in C#
    1. System.Convert (Both Types need to implement System.IConvertible)
    2. (type) operator
    3. type.ToString / type.Parse
    4. type.TryParse / type.TryParseExact

    Narrowing convertions may return incorrect result.

Boxing / Unboxing

  • Boxing converts a value type to a reference type
  • Unboxing converts a reference type to a value type
  • Boxing produces overhead
  • Boxing occures when:call of virtual members inherited from System.Object (ToString …)
  • So you should avoid boxing by:
    1. Implement Overloads for methods, instead of using an object parameter
    2. Use Generics
    3. Override ToString, Equals and GetHash when defining structures
  • Define conversions for your own types by:
    1. Conversion Operators for narrowing and widening conversions
    2. Override ToString and Parse to provide conversion
    3. Implementing System.IConvertible (For System.Convert usage and curture specific conversion)
    4. Implementing TypeConverter to use PropertyWindows (Designtime) [Not Important for Exam]
  • Example for Operators:
    struct MyType
    {
         public int TypeValue;
    
         public static implicit operator MyType(int arg)
         {
             MyType ret = new MyType();
             ret.TypeValue = arg;
             return ret;
         }
    
         public static explicit operator int(MyType arg)
         {
             return arg.TypeValue;
         }
    }
    
  • For implementing IConvertible, add to Typedefinition and implement. Throw InvalidCastException if you dont support a conversion
  • Anything new for me ?

    The part about the operators was pretty new for me. I will try to use it more often :o )

    I dont use structs very often, but good to know what to avoid when it comes to boxing and unboxing.

    Share and Enjoy:
    • Digg
    • del.icio.us
    • Mixx
    • Google Bookmarks
    • MisterWong.DE
    • Technorati
    • Webnews.de
    • YahooMyWeb

    Hinterlasse eine Antwort

    CAPTCHA-Bild CAPTCHA Audio
    Bild neuladen

    Bad Behavior has blocked 35 access attempts in the last 7 days.