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 0 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

    R Offline
    R Offline
    Rob Grainger
    wrote on last edited by
    #95

    I fail to see why that is safer. In case (a), an exception can be raised if expression is of the wrong type. That seems entirely appropriate. In case (b), if an expression of the wrong type is supplied, the result is null. If a programmer fails to check this, the result is an exception anyway. There's a place for both of them. I generally prefer errors to generate exceptions early - i.e. at the cast, rather than the point of usage. So, if I really expect the result to be of a given type I use the former. If I'm using the cast as a shorthand for checking the type is OK, then casting, I prefer the latter.

    1 Reply Last reply
    0
    • P PIEBALDconsult

      I'll code to the spec and assume hope they'll fix the implementation.

      R Offline
      R Offline
      Rob Grainger
      wrote on last edited by
      #96

      There is always a difference between spec and implementation. A language spec is designed to specify what an implementer must achieve - how they achieve it is up to them. For example, nothing in the C++ spec specifies vtables are required to implement virtual functions. The vast majority of compilers implement them that way, but a vendor is free to do things some other way.

      1 Reply Last reply
      0
      • Q Quirkafleeg

        Wrong - a is C-style casting, not C++

        S Offline
        S Offline
        SleimanJneidi
        wrote on last edited by
        #97

        No the first is compile time and the second is run time. 'as' keyword is used to RTTI

        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

          E Offline
          E Offline
          Eusebiu Marcu
          wrote on last edited by
          #98

          There's a little more than that. See here: what-s-the-difference-between-as-and-cast-operators[^]

          Eusebiu

          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
            Amit Gupta AG
            wrote on last edited by
            #99

            'B' is better, Because use of 'as' operator does not throw exception if casting is not successful where as 'A' will throw exception in case casting fails.

            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
              Daniel Vaughan
              wrote on last edited by
              #100

              Often I see the 'as' keyword misused in a way that it hides the cause of a NullReferenceException. For example, take a look at this crummy code:

              ((foo as (Light)).SwitchOn(); // bad

              If foo is not a Light, then a NullReferenceException is raised. But if foo was null to begin with, then a NullReferenceException is also raised. In either case, we can’t be certain if it is one or the other. When the ‘as’ is replaced by a direct cast, an InvalidCastException is raised when foo is not a Light; allowing us to distinguish between the two situations:

              ((Light)foo).SwitchOn(); // better

              Sometimes, therefore, the choice to use 'as' or a direct cast isn’t a choice at all.

              Daniel Vaughan Twitter | Blog | Microsoft MVP | Projects: Calcium SDK, Clog | LinkedIn

              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

                L Offline
                L Offline
                LucianPopescu
                wrote on last edited by
                #101

                I use this :

                if(e is SomeObject)
                {
                SomeObject obj = (SomeObject)e;
                }

                1 Reply Last reply
                0
                • N NormDroid

                  The final years of coding MFC, I was using the xxx_cast operators religously.

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

                  R Offline
                  R Offline
                  Rob Grainger
                  wrote on last edited by
                  #102

                  That makes a change. It seems most C++ programmers are either unaware of them, or just lazy typists. A good sign of this is that my response above seems to have been downvoted for some reason (not that I care - I find the obsession with ratings here a bit odd). Maybe my knowledge of C++ is incomplete, but I assume Stroustrup knew his intention on introducing that feature.

                  1 Reply Last reply
                  0
                  • P PIEBALDconsult

                    That's their problem.

                    R Offline
                    R Offline
                    Rob Grainger
                    wrote on last edited by
                    #103

                    Maybe, but its generally considered good form if coding an exposed API to be defensive wrt such fails by the developer using your API. Naturally, there are exceptions euch as performance critical code, where the costs of such checks outweigh the benefits of improved diagnostics. My approach is that if code is called only internally (ie. by developers working on our products), it may be safe to avoid such checks. If called externally (by third party developers), it rarely is.

                    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

                      U Offline
                      U Offline
                      User 4520523
                      wrote on last edited by
                      #104

                      Norm .net wrote:

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

                      SomeObject obj = (SomeObject) e;

                      or
                       
                      B.

                      SomeObject obj = e as SomeObject;

                      What about secret option C. use the correct one for the circumstances. While you might have been interested in which of the two we prefer, thats like asking which do you prefer: A. for B. return You might have a preference, but they aren't interchangeable. You should use A if the object has to be of the correct type. You will get an exception and your exception processing will clean up for you as best as it can. You should use B if you are expecting different types. You get a null so you try the next type. This isn't very OO but it can be useful for optimising. The code will almost always be more procedural, so you have to be careful not to over complicate it. Trying to stop exceptions being thrown at all costs is like using ON ERROR RESUME NEXT in VB. Unless you know exactly how to process an exception you shouldn't try to catch it or defend against it.

                      1 Reply Last reply
                      0
                      • H hairy_hats

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

                        O Offline
                        O Offline
                        oooshola
                        wrote on last edited by
                        #105

                        viaducting wrote:

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

                        Exactly. I believe "as" returns null if the attempt to cast was unsuccessful, while casting will produce an exception. So, for testing if the cast was successful or not: With casting, you'd need a try/catch block. But with "as" you could just test the result if it's null or not, with an if statement. (<-- arguably less code/more readable).

                        www.oooshola.com

                        B 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

                          L Offline
                          L Offline
                          Lost User
                          wrote on last edited by
                          #106

                          You are SO wrong! 1- 'As' works only with classes, it's like the dynamic_cast operator from C++, it returns null if the types do not match. 1- The static cast works both with classes and structs, but will throw an InvalidCastException if the types do not match. Hope it helps

                          Saludos!! ____Juan

                          1 Reply Last reply
                          0
                          • P PIEBALDconsult

                            That's their problem.

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

                            PIEBALDconsult wrote:

                            That's their problem.

                            If Only. Note, my two options allow for your point of view. If you want to you can use option 'a' for plug-in scenarios and let the exception bubble up till it's handled. The point I'm making is that the decision is more about communication with fellow coders than with the machine. The Compiler doesn't give a rats ass which you use. If you use the casting approach as the normal approach, it makes the alternative 'AS' approach stand out as something unusual. This *should* convey something to someone reading your code, even if that someone is you six months from now. The 'AS' approach with a check for NULL tells the reader that NULL in an occasionally expected value, not an exception. That's valuable info right there. The only thing I would advice against is using both methods interchangeably with no thought for why you use one in a given situation and not the other. -Richard

                            Hit any user to continue.

                            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

                              M Offline
                              M Offline
                              Member 3904894
                              wrote on last edited by
                              #108

                              I would prefer option B.

                              1 Reply Last reply
                              0
                              • O oooshola

                                viaducting wrote:

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

                                Exactly. I believe "as" returns null if the attempt to cast was unsuccessful, while casting will produce an exception. So, for testing if the cast was successful or not: With casting, you'd need a try/catch block. But with "as" you could just test the result if it's null or not, with an if statement. (<-- arguably less code/more readable).

                                www.oooshola.com

                                B Offline
                                B Offline
                                bNobo34
                                wrote on last edited by
                                #109

                                Potential "invisible" bugs hard to debug if you forget to test "null value" after using AS operator. Personnaly, I prefer to have an exception, even if it's a little bit more code to handle it. If I forget the error handler, there is an immediate punishment :)

                                O 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

                                  B Offline
                                  B Offline
                                  bNobo34
                                  wrote on last edited by
                                  #110

                                  "Because it's better" - InvalidArgumentException :)

                                  1 Reply Last reply
                                  0
                                  • N Nagy Vilmos

                                    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

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

                                    Oh - that white space. I happen to like separating the last line of text from the sig. In this case, I didn't put in CR's, but instead created a < div > - am not sure if that helps you. Esthetics. Beauty in the eye of the beholder. &etc.

                                    "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

                                    1 Reply Last reply
                                    0
                                    • B bNobo34

                                      Potential "invisible" bugs hard to debug if you forget to test "null value" after using AS operator. Personnaly, I prefer to have an exception, even if it's a little bit more code to handle it. If I forget the error handler, there is an immediate punishment :)

                                      O Offline
                                      O Offline
                                      oooshola
                                      wrote on last edited by
                                      #112

                                      This is true, although you'd also get a visible (semi-)immediate null reference exception when you try to use anything from the object. Plus, I personally use "as" so often that either: a) I remember to test it -- equally as well as I'd remember to use a try/catch in the other scenario, or b) when I forget/get a null reference, I remember to include failed casting as the possible culprit when debugging. I think we agree that it boils down to a "personally, I ..." kind of thing. :)

                                      www.oooshola.com

                                      B P 2 Replies 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

                                        M Offline
                                        M Offline
                                        mgordonhou
                                        wrote on last edited by
                                        #113

                                        If programming is used to express intent, then I use option A when I have no intent to check if the cast was successful; I use option B if I intend to check if the result of the cast is null.

                                        1 Reply Last reply
                                        0
                                        • O oooshola

                                          This is true, although you'd also get a visible (semi-)immediate null reference exception when you try to use anything from the object. Plus, I personally use "as" so often that either: a) I remember to test it -- equally as well as I'd remember to use a try/catch in the other scenario, or b) when I forget/get a null reference, I remember to include failed casting as the possible culprit when debugging. I think we agree that it boils down to a "personally, I ..." kind of thing. :)

                                          www.oooshola.com

                                          B Offline
                                          B Offline
                                          bNobo34
                                          wrote on last edited by
                                          #114

                                          I completly agree with you !

                                          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