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

    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
              • N NormDroid

                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 Offline
                S Offline
                Sahir Shah
                wrote on last edited by
                #63

                Somebody didn't read the subject of the post.

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

                N 1 Reply Last reply
                0
                • N Nemanja Trifunovic

                  PIEBALDconsult wrote:

                  what are you people doing?

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

                  utf8-cpp

                  J Offline
                  J Offline
                  Jim Crafton
                  wrote on last edited by
                  #64

                  You've been reading java code on the throne again haven't you? :)

                  ¡El diablo está en mis pantalones! ¡Mire, mire! SELECT * FROM User WHERE Clue > 0 0 rows returned Save an Orange - Use the VCF! Personal 3D projects Just Say No to Web 2 Point Blow

                  1 Reply Last reply
                  0
                  • S Sahir Shah

                    Somebody didn't read the subject of the post.

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

                    :wtf: are you going on about.

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

                    H S 2 Replies Last reply
                    0
                    • N NormDroid

                      I'd say more of a debate, but as we all know rules of the lounge, I'd say just go along with it and chill :)

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

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

                      I seem to have upset some voters along the way. :-D

                      N 1 Reply Last reply
                      0
                      • N NormDroid

                        :wtf: are you going on about.

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

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

                        Sahir seems to be comparing C# casts with a handler of equine animals.

                        N 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[^]

                          G Offline
                          G Offline
                          GenJerDan
                          wrote on last edited by
                          #68

                          Not that there's anything wrong with that.

                          Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life. My Mu[sic] My Films My Windows Programs, etc.

                          1 Reply Last reply
                          0
                          • H hairy_hats

                            Sahir seems to be comparing C# casts with a handler of equine animals.

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

                            :) Indeed, at this rate he's going to hit an exception that he may not like.

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

                            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

                              C Offline
                              C Offline
                              CPallini
                              wrote on last edited by
                              #70

                              I prefer directly throwing. :)

                              If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
                              This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
                              [My articles]

                              1 Reply Last reply
                              0
                              • N NormDroid

                                :wtf: are you going on about.

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

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

                                Well in brief, if you are in the shower and drop the soap and there is an operator mentioned in the subject line around, there is a good chance he might be a hominid. I wouldn't advise you to try and pick up the soap.

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

                                1 Reply Last reply
                                0
                                • P Pete OHanlon

                                  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 Offline
                                  C Offline
                                  CPallini
                                  wrote on last edited by
                                  #72

                                  Well a smart language like C# should provide the construct this way:

                                  if (e is MyObject)
                                  {
                                  // here call MyObject methods on e
                                  }

                                  :rolleyes:

                                  If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
                                  This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
                                  [My articles]

                                  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

                                    D Offline
                                    D Offline
                                    Daniel Grunwald
                                    wrote on last edited by
                                    #73

                                    I use the (cast) only when I know 'e is always SomeObject'. Which is a rare case - think stuff like (ThisClass)base.MemberwiseClone(). Otherwise, I prefer as + null check over is + cast. It looks cleaner to me, and is also more performant. 'a is T' gets compiled to the same IL as '(a as T) != null', so is + cast ends up casting twice (and last time I checked, the JIT was too dumb to optimize that).

                                    E P 2 Replies Last reply
                                    0
                                    • D Daniel Grunwald

                                      I use the (cast) only when I know 'e is always SomeObject'. Which is a rare case - think stuff like (ThisClass)base.MemberwiseClone(). Otherwise, I prefer as + null check over is + cast. It looks cleaner to me, and is also more performant. 'a is T' gets compiled to the same IL as '(a as T) != null', so is + cast ends up casting twice (and last time I checked, the JIT was too dumb to optimize that).

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

                                      Like I said, my problem is that most developers that use AS do not subsequently check for null. The fact that the .NET framework is written stupidly is a completely other rant. (IMHO AS should use IS and not the other way around).

                                      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

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

                                        Like I said, my problem is that most developers that use AS do not subsequently check for null. The fact that the .NET framework is written stupidly is a completely other rant. (IMHO AS should use IS and not the other way around).

                                        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

                                        D Offline
                                        D Offline
                                        Daniel Grunwald
                                        wrote on last edited by
                                        #75

                                        Ennis Ray Lynch, Jr. wrote:

                                        AS should use IS and not the other way around

                                        How that? 'a as B' should be compiled to 'a is B ? (B)a : null'? That would be horribly stupid. Consider how this works on the assembly level: 'is' is a function that takes an object and a type token, performs a type test, returns non-zero if successful, zero otherwise. 'as' is a function that takes an object and a type token, performs a type test, returns the object if successful, null otherwise. Given that objects are non-zero by definition, it makes perfect sense to use the same function for both, and that's exactly what .NET does. What's stupid is that the JIT optimizer is so dumb that this leads to a performance difference visible to the programmer. If the JIT could simply optimize away redundant casts, nobody would have to care what as/is/casts compile to.

                                        E 1 Reply Last reply
                                        0
                                        • D Daniel Grunwald

                                          Ennis Ray Lynch, Jr. wrote:

                                          AS should use IS and not the other way around

                                          How that? 'a as B' should be compiled to 'a is B ? (B)a : null'? That would be horribly stupid. Consider how this works on the assembly level: 'is' is a function that takes an object and a type token, performs a type test, returns non-zero if successful, zero otherwise. 'as' is a function that takes an object and a type token, performs a type test, returns the object if successful, null otherwise. Given that objects are non-zero by definition, it makes perfect sense to use the same function for both, and that's exactly what .NET does. What's stupid is that the JIT optimizer is so dumb that this leads to a performance difference visible to the programmer. If the JIT could simply optimize away redundant casts, nobody would have to care what as/is/casts compile to.

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

                                          What do you think AS is doing now?

                                          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

                                          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