Results 1 to 4 of 4

Thread: [Resolved] Casting Reference Types

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Aug 2000
    Location
    Birmingham, AL
    Posts
    1,276

    Resolved [Resolved] Casting Reference Types

    Consider:
    Code:
    Control c = new Control();
    object o = (object)c;
    Control x = (Control)o;
    and:
    Code:
    Control c = new Control();
    object o = c as object;
    Control x = o as Control;
    Is either method preferable and if so why?
    Last edited by wey97; Oct 20th, 2006 at 07:29 AM.

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Casting Reference Types

    The 'as' keyword doesn't simply cast. It will test the type of the actual object first. If the object is of the type being cast to then the cast is performed. If the object is not of that type then a null reference is returned. If you know for sure that the object is of the type that you're casting to then a straight cast is preferable because it is faster. If the types don't match though, an exception will be thrown, so if there is any doubt about the type of the object then use 'as'. Of course, the MSDN library topic for the C# 'as' keyword would have told you all that.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

    Thread Starter
    Frenzied Member
    Join Date
    Aug 2000
    Location
    Birmingham, AL
    Posts
    1,276

    Re: Casting Reference Types

    Quote Originally Posted by jmcilhinney
    Of course, the MSDN library topic for the C# 'as' keyword would have told you all that.
    I don't keep a local copy and the web site won't connect.

    Thanks for the help anyway.

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Casting Reference Types

    Quote Originally Posted by wey97
    I don't keep a local copy
    You absolutely should. I can't think of any valid reason not to.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width