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. The Lounge
  3. c# Casting v As operator

c# Casting v As operator

Scheduled Pinned Locked Moved The Lounge
csharpquestion
117 Posts 47 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.
  • N Nagy Vilmos

    I prefer as because it is safer:

    expression as type

    is equivalent to:

    expression is type ? (type)expression : (type)null

    When you use casting you can get StoopidTypeException.


    Panic, Chaos, Destruction. My work here is done. Drink. Get drunk. Fall over - P O'H OK, I will win to day or my name isn't Ethel Crudacre! - DD Ethel Crudacre I cannot live by bread alone. Bacon and ketchup are needed as well. - Trollslayer Have a bit more patience with newbies. Of course some of them act dumb - they're often *students*, for heaven's sake - Terry Pratchett

    H Offline
    H Offline
    hairy_hats
    wrote on last edited by
    #14

    Which is exactly why this is more of a programming question than a "lifestyle choice" question.

    N 1 Reply Last reply
    0
    • N NormDroid

      For those using c#, what do you prefer? A.

      SomeObject obj = (SomeObject) e;

      or B.

      SomeObject obj = e as SomeObject;

      www.software-kinetics.co.uk Wear a hard hat it's under construction

      P Offline
      P Offline
      Pete OHanlon
      wrote on last edited by
      #15

      It depends on the situation. Normally, I prefer to cast with the as operator because I don't have to catch the exception, and it just feels more natural for me to not have code like this:

      MyClass c = null;
      try
      {
      c = (MyClass)variable;
      }
      catch(InvalidCastException)
      {
      c = new MyClass();
      }

      Of course, there are times where you can't use as, so in those cases you use the () casting form.

      Forgive your enemies - it messes with their heads

      My blog | My articles | MoXAML PowerToys | Mole 2010 - debugging made easier - my favourite utility

      1 Reply Last reply
      0
      • R Ravi Bhavnani

        It depends.  (A) will throw if the cast fails while (B) will evaluate to null if the cast fails.  I use both depending on how I intend to handle the casting failure. /ravi

        My new year resolution: 2048 x 1536 Home | Articles | My .NET bits | Freeware ravib(at)ravib(dot)com

        R Offline
        R Offline
        realJSOP
        wrote on last edited by
        #16

        Correct answer.

        ".45 ACP - because shooting twice is just silly" - JSOP, 2010
        -----
        You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
        -----
        "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass." - Dale Earnhardt, 1997

        1 Reply Last reply
        0
        • N Nagy Vilmos

          I prefer as because it is safer:

          expression as type

          is equivalent to:

          expression is type ? (type)expression : (type)null

          When you use casting you can get StoopidTypeException.


          Panic, Chaos, Destruction. My work here is done. Drink. Get drunk. Fall over - P O'H OK, I will win to day or my name isn't Ethel Crudacre! - DD Ethel Crudacre I cannot live by bread alone. Bacon and ketchup are needed as well. - Trollslayer Have a bit more patience with newbies. Of course some of them act dumb - they're often *students*, for heaven's sake - Terry Pratchett

          P Offline
          P Offline
          Peter Mulholland
          wrote on last edited by
          #17

          I did not know this. I'm currently working on stuff with a common base interface with multipe derived interfaces and I've been playing about with GetType and typeof to try to get the correct derived interface from a base interface. So reading lounge posts may have been productive today. :-D

          Pete

          1 Reply Last reply
          0
          • D Dalek Dave

            No, I think it more of a lifestyle choice question.

            ------------------------------------ I will never again mention that I was the poster of the One Millionth Lounge Post, nor that it was complete drivel. Dalek Dave CCC Link[^] Trolls[^]

            H Offline
            H Offline
            hairy_hats
            wrote on last edited by
            #18

            No, because the two are not equivalent (see other posts below).

            O 1 Reply Last reply
            0
            • N NormDroid

              Hardly :|

              www.software-kinetics.co.uk Wear a hard hat it's under construction

              H Offline
              H Offline
              hairy_hats
              wrote on last edited by
              #19

              If a noob had asked that question in the Lounge they'd have been toast.

              N 1 Reply Last reply
              0
              • N NormDroid

                For those using c#, what do you prefer? A.

                SomeObject obj = (SomeObject) e;

                or B.

                SomeObject obj = e as SomeObject;

                www.software-kinetics.co.uk Wear a hard hat it's under construction

                A Offline
                A Offline
                Aamir Butt
                wrote on last edited by
                #20

                B. Because apart from what others have mentioned in favor of b, it will automagically do a QueryInterface as well in case of a COM interface call.

                A year spent in artificial intelligence is enough to make one believe in God

                N 1 Reply Last reply
                0
                • N NormDroid

                  True, but you should know beforehand if the casting is correct.

                  www.software-kinetics.co.uk Wear a hard hat it's under construction

                  R Offline
                  R Offline
                  Ravi Bhavnani
                  wrote on last edited by
                  #21

                  Norm .net wrote:

                  True, but you should know beforehand if the casting is correct.

                  "Should" is a dangerous word. :) A plugin discovery mechanism (that makes extensive use of reflection) I recently built assumes nothing regarding the type of object that was loaded. /ravi

                  My new year resolution: 2048 x 1536 Home | Articles | My .NET bits | Freeware ravib(at)ravib(dot)com

                  1 Reply Last reply
                  0
                  • W W Balboos GHB

                    Sorry - wrong. The answer's a, because it's better.

                    "The difference between genius and stupidity is that genius has its limits." - Albert Einstein

                    "As far as we know, our computer has never had an undetected error." - Weisert

                    "If you are searching for perfection in others, then you seek disappointment. If you are seek perfection in yourself, then you will find failure." - Balboos HaGadol Mar 2010

                    N Offline
                    N Offline
                    Nagy Vilmos
                    wrote on last edited by
                    #22

                    There seems to be alot of white space in your sig.


                    Panic, Chaos, Destruction. My work here is done. Drink. Get drunk. Fall over - P O'H OK, I will win to day or my name isn't Ethel Crudacre! - DD Ethel Crudacre I cannot live by bread alone. Bacon and ketchup are needed as well. - Trollslayer Have a bit more patience with newbies. Of course some of them act dumb - they're often *students*, for heaven's sake - Terry Pratchett

                    W 1 Reply Last reply
                    0
                    • H hairy_hats

                      If a noob had asked that question in the Lounge they'd have been toast.

                      N Offline
                      N Offline
                      NormDroid
                      wrote on last edited by
                      #23

                      It's a debate, not a question.

                      www.software-kinetics.co.uk Wear a hard hat it's under construction

                      N 1 Reply Last reply
                      0
                      • A Aamir Butt

                        B. Because apart from what others have mentioned in favor of b, it will automagically do a QueryInterface as well in case of a COM interface call.

                        A year spent in artificial intelligence is enough to make one believe in God

                        N Offline
                        N Offline
                        NormDroid
                        wrote on last edited by
                        #24

                        Good point, I suppose not many noobies would know about QueryInterface, ah those were the days. :)

                        www.software-kinetics.co.uk Wear a hard hat it's under construction

                        A 1 Reply Last reply
                        0
                        • N NormDroid

                          For those using c#, what do you prefer? A.

                          SomeObject obj = (SomeObject) e;

                          or B.

                          SomeObject obj = e as SomeObject;

                          www.software-kinetics.co.uk Wear a hard hat it's under construction

                          R Offline
                          R Offline
                          Richard A Dalton
                          wrote on last edited by
                          #25

                          If an illegal cast is an exceptional (woah, that should never happen) situation, then (a) If there's a possibility that through normal use the cast might be invalid (e.g. Plug-in tpye code), then (b), followed by an If to check for Null. -Richard

                          Hit any user to continue.

                          N P 2 Replies Last reply
                          0
                          • N NormDroid

                            Good point, I suppose not many noobies would know about QueryInterface, ah those were the days. :)

                            www.software-kinetics.co.uk Wear a hard hat it's under construction

                            A Offline
                            A Offline
                            Aamir Butt
                            wrote on last edited by
                            #26

                            Yeah... I always ended up using CComPtr to avoid reference-leak issues. MS should have banned direct use of QueryInterface and CoCreateInstance anyway. RAII should have been the way from onset.

                            A year spent in artificial intelligence is enough to make one believe in God

                            N 1 Reply Last reply
                            0
                            • A Aamir Butt

                              Yeah... I always ended up using CComPtr to avoid reference-leak issues. MS should have banned direct use of QueryInterface and CoCreateInstance anyway. RAII should have been the way from onset.

                              A year spent in artificial intelligence is enough to make one believe in God

                              N Offline
                              N Offline
                              NormDroid
                              wrote on last edited by
                              #27

                              I used raw COM when the COM specs where first released, wow you needed a ton of code to do a small task. But it did give me background on the workings of COM.

                              www.software-kinetics.co.uk Wear a hard hat it's under construction

                              A 1 Reply Last reply
                              0
                              • R Richard A Dalton

                                If an illegal cast is an exceptional (woah, that should never happen) situation, then (a) If there's a possibility that through normal use the cast might be invalid (e.g. Plug-in tpye code), then (b), followed by an If to check for Null. -Richard

                                Hit any user to continue.

                                N Offline
                                N Offline
                                NormDroid
                                wrote on last edited by
                                #28

                                Richard A. Dalton wrote:

                                Plug-in tpye code

                                That's the only situation I could eve think off, normally you should be aware if the cast would fail or not.

                                www.software-kinetics.co.uk Wear a hard hat it's under construction

                                1 Reply Last reply
                                0
                                • N NormDroid

                                  I used raw COM when the COM specs where first released, wow you needed a ton of code to do a small task. But it did give me background on the workings of COM.

                                  www.software-kinetics.co.uk Wear a hard hat it's under construction

                                  A Offline
                                  A Offline
                                  Aamir Butt
                                  wrote on last edited by
                                  #29

                                  Norm .net wrote:

                                  wow you needed a ton of code to do a small task

                                  Check the section "Master Programmer" in this link. :)[^]

                                  A year spent in artificial intelligence is enough to make one believe in God

                                  N 1 Reply Last reply
                                  0
                                  • N NormDroid

                                    For those using c#, what do you prefer? A.

                                    SomeObject obj = (SomeObject) e;

                                    or B.

                                    SomeObject obj = e as SomeObject;

                                    www.software-kinetics.co.uk Wear a hard hat it's under construction

                                    D Offline
                                    D Offline
                                    Dave Parker
                                    wrote on last edited by
                                    #30

                                    It depends on what you're trying to do, the two things are different. If you're certain e is a SomeObject then I'd cast it. If it may or may not be I'd usually use the as keyword, in which case obj would be null if it isn't a SomeObject as opposed to throwing an exception.

                                    1 Reply Last reply
                                    0
                                    • N Nagy Vilmos

                                      There seems to be alot of white space in your sig.


                                      Panic, Chaos, Destruction. My work here is done. Drink. Get drunk. Fall over - P O'H OK, I will win to day or my name isn't Ethel Crudacre! - DD Ethel Crudacre I cannot live by bread alone. Bacon and ketchup are needed as well. - Trollslayer Have a bit more patience with newbies. Of course some of them act dumb - they're often *students*, for heaven's sake - Terry Pratchett

                                      W Offline
                                      W Offline
                                      W Balboos GHB
                                      wrote on last edited by
                                      #31

                                      Possibly a font-problem on your end? It looks roughly like: W**.'.** Balboos - the three punctuation-like characters being the HTML character code: & there4; (space put in after & so it doesn't render)

                                      "The difference between genius and stupidity is that genius has its limits." - Albert Einstein

                                      "As far as we know, our computer has never had an undetected error." - Weisert

                                      "If you are searching for perfection in others, then you seek disappointment. If you are seek perfection in yourself, then you will find failure." - Balboos HaGadol Mar 2010

                                      N 1 Reply Last reply
                                      0
                                      • A Aamir Butt

                                        Norm .net wrote:

                                        wow you needed a ton of code to do a small task

                                        Check the section "Master Programmer" in this link. :)[^]

                                        A year spent in artificial intelligence is enough to make one believe in God

                                        N Offline
                                        N Offline
                                        NormDroid
                                        wrote on last edited by
                                        #32

                                        Oh that brings back memories, and forgetting idl files :)

                                        www.software-kinetics.co.uk Wear a hard hat it's under construction

                                        1 Reply Last reply
                                        0
                                        • W W Balboos GHB

                                          Possibly a font-problem on your end? It looks roughly like: W**.'.** Balboos - the three punctuation-like characters being the HTML character code: & there4; (space put in after & so it doesn't render)

                                          "The difference between genius and stupidity is that genius has its limits." - Albert Einstein

                                          "As far as we know, our computer has never had an undetected error." - Weisert

                                          "If you are searching for perfection in others, then you seek disappointment. If you are seek perfection in yourself, then you will find failure." - Balboos HaGadol Mar 2010

                                          N Offline
                                          N Offline
                                          Nagy Vilmos
                                          wrote on last edited by
                                          #33

                                          Not your name, your sig:

                                          W∴ Balboos wrote:

                                          Possibly a font-problem on your end?
                                           
                                          It looks roughly like: W**.'.** Balboos - the three punctuation-like characters being the HTML character code: & there4; (space put in after & so it doesn't render)

                                          "The difference between genius and stupidity is that genius has its limits." - Albert Einstein

                                          "As far as we know, our computer has never had an undetected error." - Weisert

                                          "If you are searching for perfection in others, then you seek disappointment. If you are seek perfection in yourself, then you will find failure." - Balboos HaGadol Mar 2010

                                          There's a lot of white space...


                                          Panic, Chaos, Destruction. My work here is done. Drink. Get drunk. Fall over - P O'H OK, I will win to day or my name isn't Ethel Crudacre! - DD Ethel Crudacre I cannot live by bread alone. Bacon and ketchup are needed as well. - Trollslayer Have a bit more patience with newbies. Of course some of them act dumb - they're often *students*, for heaven's sake - Terry Pratchett

                                          S W 2 Replies 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