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

    S Offline
    S Offline
    Sahir Shah
    wrote on last edited by
    #43

    The second one sounds like some kind of hominid comrade Norm.

    Und wenn du lange in einen abgrund blickst, blickt der Abgrund auch in dich hinein.

    N 1 Reply Last reply
    0
    • F Fabio Franco

      If you do know something is not gonna be null, the cast is more efficient.

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

      To add... and the cast is a qualified cast.

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

      1 Reply Last reply
      0
      • S Sahir Shah

        The second one sounds like some kind of hominid comrade Norm.

        Und wenn du lange in einen abgrund blickst, blickt der Abgrund auch in dich hinein.

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

        Don't fancy seeing your code if you think b. looks like a great ape :rolleyes:

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

        S 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

          OriginalGriffO Offline
          OriginalGriffO Offline
          OriginalGriff
          wrote on last edited by
          #46

          B. I don't like to rely on exceptions for normal processing (they are slow and clumsy for that), so you have to check for null.

          SomeObject obj = e as SomeObject;
          if (obj != null)
          {
          ...
          }

          While

          if (e != null && e is SomeObject)
          {
          SomeObject obj = (SomeObject) e;
          ...
          }

          looks ugly. Plus, if you are going to use obj as a SomeObject instance, then the former is quicker since there is only one check on the type of e

          Real men don't use instructions. They are only the manufacturers opinion on how to put the thing together. Manfred R. Bihy: "Looks as if OP is learning resistant."

          "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
          "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

          P 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

            J Offline
            J Offline
            jim lahey
            wrote on last edited by
            #47

            I'm with Ravi on this one.I use both, the decision if which one to use is purely based upon what I need to happen should it go wrong

            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

              S Offline
              S Offline
              Sahir Shah
              wrote on last edited by
              #48

              He's doin it on purpose to annoy you Senhor Vilmos. I thought you would have figured that out by now :D

              Und wenn du lange in einen abgrund blickst, blickt der Abgrund auch in dich hinein.

              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

                N Offline
                N Offline
                Nemanja Trifunovic
                wrote on last edited by
                #49

                It is not about preference. When I want an exception in case of type error I use A., and if I want a null I use B. I don't see a point of something like:

                SomeObj obj = e as SomeObject;
                if (obj == null)
                throw new InvalidCastException();

                Of course, in good languages casting is almost always a sign of a design error.

                utf8-cpp

                P 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.

                  P Offline
                  P Offline
                  PIEBALDconsult
                  wrote on last edited by
                  #50

                  Richard A. Dalton wrote:

                  Plug-in tpye code

                  I don't have such problems with plug-ins.

                  P 1 Reply Last reply
                  0
                  • OriginalGriffO OriginalGriff

                    B. I don't like to rely on exceptions for normal processing (they are slow and clumsy for that), so you have to check for null.

                    SomeObject obj = e as SomeObject;
                    if (obj != null)
                    {
                    ...
                    }

                    While

                    if (e != null && e is SomeObject)
                    {
                    SomeObject obj = (SomeObject) e;
                    ...
                    }

                    looks ugly. Plus, if you are going to use obj as a SomeObject instance, then the former is quicker since there is only one check on the type of e

                    Real men don't use instructions. They are only the manufacturers opinion on how to put the thing together. Manfred R. Bihy: "Looks as if OP is learning resistant."

                    P Offline
                    P Offline
                    PIEBALDconsult
                    wrote on last edited by
                    #51

                    OriginalGriff wrote:

                    (they are slow and clumsy for that

                    No they're not.

                    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
                      Mike Hankey
                      wrote on last edited by
                      #52

                      I used to use A (C upbringing) now I kinda favor B.

                      I Haven't Gone To Bed With Any Ugly Women, but I've Sure Woke Up With A Few.

                      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
                        PIEBALDconsult
                        wrote on last edited by
                        #53

                        Depends on the situation. Mostly proper casting, as occasionally, particularly when checking for a derived type.

                        1 Reply Last reply
                        0
                        • N NormDroid

                          :beer:

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

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

                          Don't mind if I do. :beer: yourself.


                          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

                          1 Reply Last reply
                          0
                          • N NormDroid

                            The hand is quicker than the I eye.

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

                            S Offline
                            S Offline
                            Sahir Shah
                            wrote on last edited by
                            #55

                            Norm .net wrote:

                            The hand is quicker than the I eye

                            Too much hand is bad for the eye.

                            Und wenn du lange in einen abgrund blickst, blickt der Abgrund auch in dich hinein.

                            1 Reply Last reply
                            0
                            • N Nemanja Trifunovic

                              It is not about preference. When I want an exception in case of type error I use A., and if I want a null I use B. I don't see a point of something like:

                              SomeObj obj = e as SomeObject;
                              if (obj == null)
                              throw new InvalidCastException();

                              Of course, in good languages casting is almost always a sign of a design error.

                              utf8-cpp

                              P Offline
                              P Offline
                              PIEBALDconsult
                              wrote on last edited by
                              #56

                              I use A and never get an Exception, what are you people doing? :confused:

                              N 1 Reply Last reply
                              0
                              • P PIEBALDconsult

                                I use A and never get an Exception, what are you people doing? :confused:

                                N Offline
                                N Offline
                                Nemanja Trifunovic
                                wrote on last edited by
                                #57

                                PIEBALDconsult wrote:

                                what are you people doing?

                                SomeType obj = (SomeType)BloatedUglyUnreadableFrameworkFactory.CreateObject(someXMLStringThatIHopeWorksSometimesButNeverKnowForSure);

                                utf8-cpp

                                J 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

                                  E Offline
                                  E Offline
                                  Ennis Ray Lynch Jr
                                  wrote on last edited by
                                  #58

                                  As is for poor programmers. If you know that e always is SomeObject then e should be typed as such using some other method. Otherwise you always have to check the result of the as operation. So then you have the following two scenarios which must always be in case A or case B:

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

                                  or

                                  SomeObject someobject = e as SomeObject;
                                  if(someObject != null){

                                  }

                                  But then in case by I always here the response ... but I know e is always SomeObject. Really then maybe it should be defined as such. The AS operator is designed solely to support developers that don't have a fundamental concept of type. After all, for all of the time I have seen the is operator used with a subsequent cast, checking for null after the AS is a white rhinoceros.

                                  Need custom software developed? I do custom programming based primarily on MS tools with an emphasis on C# development and consulting. I also do Android Programming as I find it a refreshing break from the MS. "And they, since they Were not the one dead, turned to their affairs" -- Robert Frost

                                  P D P 3 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

                                    P Offline
                                    P Offline
                                    peterchen
                                    wrote on last edited by
                                    #59

                                    The first when I need the exception, the second when I need the null. Because face it, e is never what you need it to be.

                                    FILETIME to time_t
                                    | FoldWithUs! | sighist | WhoIncludes - Analyzing C++ include file hierarchy

                                    L 1 Reply Last reply
                                    0
                                    • E Ennis Ray Lynch Jr

                                      As is for poor programmers. If you know that e always is SomeObject then e should be typed as such using some other method. Otherwise you always have to check the result of the as operation. So then you have the following two scenarios which must always be in case A or case B:

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

                                      or

                                      SomeObject someobject = e as SomeObject;
                                      if(someObject != null){

                                      }

                                      But then in case by I always here the response ... but I know e is always SomeObject. Really then maybe it should be defined as such. The AS operator is designed solely to support developers that don't have a fundamental concept of type. After all, for all of the time I have seen the is operator used with a subsequent cast, checking for null after the AS is a white rhinoceros.

                                      Need custom software developed? I do custom programming based primarily on MS tools with an emphasis on C# development and consulting. I also do Android Programming as I find it a refreshing break from the MS. "And they, since they Were not the one dead, turned to their affairs" -- Robert Frost

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

                                      Thanks Ennis - I'm a poor programmer then because I use as, rather than the double cast, which is doing the same work again. What happens internally with as is that it checks to see if the variable is of the type, and if it is it returns a non-null pointer to that type. With the is operator, you check to see if it is of the type and then you cast it - which still determines internally whether or not it belongs to that type (this is how it throws an InvalidTypeException). In any case where you are using code-discovery, such as IoC, then the as call is more efficient. [Edit]I should add that this relates to our plugin code where the client provides their own logic, and "forgets" to implement the appropriate interfaces.[/Edit]

                                      Forgive your enemies - it messes with their heads

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

                                      modified on Thursday, June 23, 2011 9:30 AM

                                      C P 2 Replies Last reply
                                      0
                                      • P PIEBALDconsult

                                        Richard A. Dalton wrote:

                                        Plug-in tpye code

                                        I don't have such problems with plug-ins.

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

                                        You have better clients than we do then. You tell them, you must implement this interface in order for this to work, and bam they completely fail to implement the interface.

                                        Forgive your enemies - it messes with their heads

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

                                        P 1 Reply Last reply
                                        0
                                        • P peterchen

                                          The first when I need the exception, the second when I need the null. Because face it, e is never what you need it to be.

                                          FILETIME to time_t
                                          | FoldWithUs! | sighist | WhoIncludes - Analyzing C++ include file hierarchy

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

                                          peterchen wrote:

                                          Because face it, e is never what you need it to be.

                                          Not according to Pompey's review of his day at the races.

                                          Every man can tell how many goats or sheep he possesses, but not how many friends.

                                          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