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.
  • 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
                          • 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
                            Mark Hurd
                            wrote on last edited by
                            #115

                            For VB.NET users, the equivalent is: A.

                            Dim obj As SomeObject = CType(e, SomeObject)

                            or more accurately

                            Dim obj As SomeObject = DirectCast(e, SomeObject)

                            or B.

                            Dim obj As SomeObject = TryCast(e, SomeObject)

                            although VB.NET does not support SomeObject being a nullable value type. And FYI my answer is the same as most of the others, you use what is necessary depending upon the task at hand :-)

                            Regards, Mark Hurd, B.Sc.(Ma.) (Hons.)

                            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

                              P Offline
                              P Offline
                              patbob
                              wrote on last edited by
                              #116

                              "you'd also get a visible (semi-)immediate null reference exception when you try to use anything from the object." The null reference exception could potentially happen a long time later in code far, far away from the original As. Depending entirely on how the As result is used, of course. Probably the better question is about the other developers that work on the code. Will they know to assume failed casting is a possiblity? What if they're preference is cast/catch? MS probably went too far in allowing there to be two different ways to do the same thing that behave differently. Sure its more convenient, but its also potentially confusing when there's multiple developers.

                              patbob

                              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

                                J Offline
                                J Offline
                                johannesnestler
                                wrote on last edited by
                                #117

                                This is no questions of preference: 1. You can not use "as" on value types 2. For reference types you can use "as" or "cast" but with different behaviour. (returns null or exception) So it depends on the situation and the problem and NOT on your preference. Other commenters think that it depends on coding style (test for null or exception), but for me this is no question of style. I want an exception to occur only if something unexpected happen. If downstream the whole code would break if the object is null - I will use the pattern cast-try-catch. If beeing null won't break the code or can be expected I will use "as". So my point is: each of the possibilities to convert the type of an object is useful in different circumstances and these do not depend on my taste or style.

                                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