Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. What's the difference using a cast or C#'s 'as' [modified]

What's the difference using a cast or C#'s 'as' [modified]

Scheduled Pinned Locked Moved C#
csharpsalesperformancequestion
12 Posts 6 Posters 1 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M Martin Hart Turner

    Hi: I see in lots of sample code something like this:

    Customer customer = (Customer)e.NewObject;

    but I always prefer:

    Customer customer = e.NewObject as Customer;

    I can then test for 'customer' being null, but is there and *real* difference of performance hit?

    --- Regards, Martin.

    modified on Monday, November 24, 2008 4:53 AM

    B Offline
    B Offline
    Baconbutty
    wrote on last edited by
    #2

    Proximity to Programming Question Alert!

    My new favourite phrase - "misdirected leisure activity"

    L 1 Reply Last reply
    0
    • M Martin Hart Turner

      Hi: I see in lots of sample code something like this:

      Customer customer = (Customer)e.NewObject;

      but I always prefer:

      Customer customer = e.NewObject as Customer;

      I can then test for 'customer' being null, but is there and *real* difference of performance hit?

      --- Regards, Martin.

      modified on Monday, November 24, 2008 4:53 AM

      S Offline
      S Offline
      Simon P Stevens
      wrote on last edited by
      #3

      throw new ProgrammingQuestionInLoungeException();

      But I'll give you a hint - write a loop and test each method 1000 times. Time it with a Stopwatch. In a managed language all your assumptions about performance are irrelevant, the JIT compiler may be optimising stuff all over the place. Make sure your running your test in release mode.

      Simon

      M 1 Reply Last reply
      0
      • B Baconbutty

        Proximity to Programming Question Alert!

        My new favourite phrase - "misdirected leisure activity"

        L Offline
        L Offline
        leppie
        wrote on last edited by
        #4

        1 bogey at 11'!

        xacc.ide - now with TabsToSpaces support
        IronScheme - 1.0 beta 1 - out now!
        ((lambda (x) `((lambda (x) ,x) ',x)) '`((lambda (x) ,x) ',x))

        1 Reply Last reply
        0
        • S Simon P Stevens

          throw new ProgrammingQuestionInLoungeException();

          But I'll give you a hint - write a loop and test each method 1000 times. Time it with a Stopwatch. In a managed language all your assumptions about performance are irrelevant, the JIT compiler may be optimising stuff all over the place. Make sure your running your test in release mode.

          Simon

          M Offline
          M Offline
          Martin Hart Turner
          wrote on last edited by
          #5

          Ouch!! I seem to have trodden on someones toes :sigh: It was meant to be rhetorical and to see what users preffered and why, not a technical (try timing it!) question. Oh well, I thouhjt it was interesting...

          --- Regards, Martin.

          J S 2 Replies Last reply
          0
          • M Martin Hart Turner

            Ouch!! I seem to have trodden on someones toes :sigh: It was meant to be rhetorical and to see what users preffered and why, not a technical (try timing it!) question. Oh well, I thouhjt it was interesting...

            --- Regards, Martin.

            J Offline
            J Offline
            James Simpson
            wrote on last edited by
            #6

            'as' is used when the instance you are checking may not of the expected type. E.g Your expecting an 'object' but want it to be a specific type (or maybe one of many types) for a function parameter but the caller may pass in a type you dont want or expect, so you can treat is as null by casting it with the as keyword. An example of this may be when overriding the Equals method on System.Object The () cast method is more effecient becuase as compiles down to a set of IL instructions that include checking the type before attempting the cast, or returning null, eg:

            Customer customer = null;
            if(e.SomeObject is Customer)
            customer = (Customer)e.SomeObject;
            else
            customer = null;

            So, I would say 'as' has its place, but its not a replacement for a () cast. Its probably used by certain people becuase they consider it easier to read, rather than actually need to use it. James

            James Simpson Web Developer imebgo@hotmail.com P S - This is what part of the alphabet would look like if Q and R were eliminated
            Mitch Hedberg

            S 1 Reply Last reply
            0
            • M Martin Hart Turner

              Hi: I see in lots of sample code something like this:

              Customer customer = (Customer)e.NewObject;

              but I always prefer:

              Customer customer = e.NewObject as Customer;

              I can then test for 'customer' being null, but is there and *real* difference of performance hit?

              --- Regards, Martin.

              modified on Monday, November 24, 2008 4:53 AM

              C Offline
              C Offline
              Chris Maunder
              wrote on last edited by
              #7

              I'm going to move this to the C# forum, but first an answer: Do

              MyObject thing = new MyObject();

              // 1.
              MyOtherObject otherThing = thing as MyOtherObject;

              // 2.
              MyOtherObject otherThing = (MyOtherObject) thing;

              1 will have otherThing == null. 2 will throw an exception. 1 allows you (in conjunction with is to write safe, polite code that handles bad casts intelligently. 2 just barfs on the carpet like a mangy cat.

              cheers, Chris Maunder

              CodeProject.com : C++ MVP

              1 Reply Last reply
              0
              • M Martin Hart Turner

                Ouch!! I seem to have trodden on someones toes :sigh: It was meant to be rhetorical and to see what users preffered and why, not a technical (try timing it!) question. Oh well, I thouhjt it was interesting...

                --- Regards, Martin.

                S Offline
                S Offline
                Simon P Stevens
                wrote on last edited by
                #8

                Sorry if I read it wrong, it just seemed like a I can't be bothered to figure it out myself kind of question. (We get a lot of them around here) No offence intended. :) I cast if I know that the type is right, but us 'as' if I need to check. At a guess, I would say the casting is faster if it works, but slower if it throws an exception because it fails. But like I said before, with managed languages all guesses are off really. The only way that you can be certain about it is to test it.

                Simon

                M 1 Reply Last reply
                0
                • J James Simpson

                  'as' is used when the instance you are checking may not of the expected type. E.g Your expecting an 'object' but want it to be a specific type (or maybe one of many types) for a function parameter but the caller may pass in a type you dont want or expect, so you can treat is as null by casting it with the as keyword. An example of this may be when overriding the Equals method on System.Object The () cast method is more effecient becuase as compiles down to a set of IL instructions that include checking the type before attempting the cast, or returning null, eg:

                  Customer customer = null;
                  if(e.SomeObject is Customer)
                  customer = (Customer)e.SomeObject;
                  else
                  customer = null;

                  So, I would say 'as' has its place, but its not a replacement for a () cast. Its probably used by certain people becuase they consider it easier to read, rather than actually need to use it. James

                  James Simpson Web Developer imebgo@hotmail.com P S - This is what part of the alphabet would look like if Q and R were eliminated
                  Mitch Hedberg

                  S Offline
                  S Offline
                  Simon P Stevens
                  wrote on last edited by
                  #9

                  James Simpson wrote:

                  The () cast method is more effecient becuase as compiles down to a set of IL instructions that include checking the type before attempting the cast, or returning null, eg:

                  A cast doesn't perform checks or return null. A cast will throw an InvalidCastException if the types aren't castable.

                  Simon

                  J 1 Reply Last reply
                  0
                  • S Simon P Stevens

                    James Simpson wrote:

                    The () cast method is more effecient becuase as compiles down to a set of IL instructions that include checking the type before attempting the cast, or returning null, eg:

                    A cast doesn't perform checks or return null. A cast will throw an InvalidCastException if the types aren't castable.

                    Simon

                    J Offline
                    J Offline
                    James Simpson
                    wrote on last edited by
                    #10

                    the 'as' cast compiles down to the 'is' check

                    James Simpson Web Developer imebgo@hotmail.com P S - This is what part of the alphabet would look like if Q and R were eliminated
                    Mitch Hedberg

                    S 1 Reply Last reply
                    0
                    • J James Simpson

                      the 'as' cast compiles down to the 'is' check

                      James Simpson Web Developer imebgo@hotmail.com P S - This is what part of the alphabet would look like if Q and R were eliminated
                      Mitch Hedberg

                      S Offline
                      S Offline
                      Simon P Stevens
                      wrote on last edited by
                      #11

                      Ahh...It's confusing talking about keywords like 'as' that appear naturally in sentences. :laugh:

                      Simon

                      1 Reply Last reply
                      0
                      • S Simon P Stevens

                        Sorry if I read it wrong, it just seemed like a I can't be bothered to figure it out myself kind of question. (We get a lot of them around here) No offence intended. :) I cast if I know that the type is right, but us 'as' if I need to check. At a guess, I would say the casting is faster if it works, but slower if it throws an exception because it fails. But like I said before, with managed languages all guesses are off really. The only way that you can be certain about it is to test it.

                        Simon

                        M Offline
                        M Offline
                        Martin Hart Turner
                        wrote on last edited by
                        #12

                        Simon: Certainly, no offence taken :-D What's more I liked the answer you gave, very informative: Thanks.

                        --- Regards, Martin.

                        1 Reply Last reply
                        0
                        Reply
                        • Reply as topic
                        Log in to reply
                        • Oldest to Newest
                        • Newest to Oldest
                        • Most Votes


                        • Login

                        • Don't have an account? Register

                        • Login or register to search.
                        • First post
                          Last post
                        0
                        • Categories
                        • Recent
                        • Tags
                        • Popular
                        • World
                        • Users
                        • Groups