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

    A Offline
    A Offline
    AspDotNetDev
    wrote on last edited by
    #78

    Like others have mentioned, us "as" when the object may be the wrong type. Also, "as" cannot be used for non-reference types (e.g., int).

    Help a brotha out and vote Managing Your JavaScript Library in ASP.NET as the best ASP.NET article of May 2011.

    1 Reply Last reply
    0
    • H hairy_hats

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

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

      It all balances out in the long run :)

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

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

        Hear hear! Except for that I don't like your first example; I do that to pass the cast value to another method.

        if(e is SomeObject){
        F ( (SomeObject) e ) ;
        }

        If I'm setting a variable or field I use as.

        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

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

          Pete O'Hanlon wrote:

          and "forgets" to implement the appropriate interfaces.

          Then you throw an Exception and don't allow that malformed plug-in.

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

            "Note that the as operator only performs reference conversions and boxing conversions. The as operator cannot perform other conversions, such as user-defined conversions, which should instead be performed using cast expressions." Two of three C# books I have here don't mention as at all.

            1 Reply 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).

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

              " More formally, an expression of the form, Copyexpression as type is equivalent to, Copyexpression is type ? (type)expression : (type)null " http://msdn.microsoft.com/en-us/library/cscsdfbt(v=VS.80).aspx[^]

              D 1 Reply Last reply
              0
              • P PIEBALDconsult

                " More formally, an expression of the form, Copyexpression as type is equivalent to, Copyexpression is type ? (type)expression : (type)null " http://msdn.microsoft.com/en-us/library/cscsdfbt(v=VS.80).aspx[^]

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

                Yes that's the specification of the behavior, but not how it's implemented.

                Eric Lippert wrote:

                The specification is clear on this point; as (in the non-dynamic case) is defined as a syntactic sugar for is. However, in practice the CLR provides us instruction isinst, which ironically acts like as. Therefore we have an instruction which implements the semantics of as pretty well, from which we can build an implementation of is. In short, de jure is is is, and as is as is is, but de facto is is as and as is isinst.

                http://blogs.msdn.com/b/ericlippert/archive/2010/09/16/is-is-as-or-is-as-is.aspx[^]

                P 1 Reply Last reply
                0
                • P Pete OHanlon

                  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 Offline
                  P Offline
                  PIEBALDconsult
                  wrote on last edited by
                  #85

                  That's their problem.

                  R R 2 Replies Last reply
                  0
                  • N Nemanja Trifunovic

                    PIEBALDconsult wrote:

                    what are you people doing?

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

                    utf8-cpp

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

                    That deserves to blow up. What do you do once you've determined that it didn't work? Don't you just throw an Exception anyway?

                    1 Reply Last reply
                    0
                    • D Daniel Grunwald

                      Yes that's the specification of the behavior, but not how it's implemented.

                      Eric Lippert wrote:

                      The specification is clear on this point; as (in the non-dynamic case) is defined as a syntactic sugar for is. However, in practice the CLR provides us instruction isinst, which ironically acts like as. Therefore we have an instruction which implements the semantics of as pretty well, from which we can build an implementation of is. In short, de jure is is is, and as is as is is, but de facto is is as and as is isinst.

                      http://blogs.msdn.com/b/ericlippert/archive/2010/09/16/is-is-as-or-is-as-is.aspx[^]

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

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

                      R 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

                        F Offline
                        F Offline
                        franky1987
                        wrote on last edited by
                        #88

                        b. it's better, because if the cast is wrong, the member would be null ... so you don't have to surround your code with a "try {} catch {}" every few lines. :)

                        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
                          RupeshSingh
                          wrote on last edited by
                          #89

                          For reference Type, should have to use 'As' operator because of if casting is not compatible with target Object then it return null while 'Casting' throws an exception. For Value Type,'As' operator doesnot work.

                          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
                            Nchek2000
                            wrote on last edited by
                            #90

                            Refer to this page:http://weblogs.asp.net/srkirkland/archive/2007/10/29/net-2-0-cast-operator-vs-as-operator.aspx[^] using As will return null if it fail to cast.

                            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

                              T Offline
                              T Offline
                              Tom Chantler
                              wrote on last edited by
                              #91

                              I guess this wasn't a serious question, but just in case somebody who doesn't know looks in, I prefer b as it won't throw an exception if the conversion is not possible, but rather will return a null. According to MSDN[^] it's equivalent to this: expression is type ? (type)expression : (type)null but expression is only evaluated once.

                              N 1 Reply Last reply
                              0
                              • T Tom Chantler

                                I guess this wasn't a serious question, but just in case somebody who doesn't know looks in, I prefer b as it won't throw an exception if the conversion is not possible, but rather will return a null. According to MSDN[^] it's equivalent to this: expression is type ? (type)expression : (type)null but expression is only evaluated once.

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

                                I suppose my argument on that, is the programmer should know if conversion will take place or not, than letting the code take control.

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

                                1 Reply Last reply
                                0
                                • N NormDroid

                                  Splitting hairs :)

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

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

                                  Not really, C style casts are not recommended in C++ last I checked. Its preferred to use the C++ casts dynamic_cast<T>(x), static_cast<T>(x), reinterpret_Cast<T>(x) and const_cast<T>(x) as they make the intention more explicit. See : Stroustrup[^]

                                  N 1 Reply Last reply
                                  0
                                  • R Rob Grainger

                                    Not really, C style casts are not recommended in C++ last I checked. Its preferred to use the C++ casts dynamic_cast<T>(x), static_cast<T>(x), reinterpret_Cast<T>(x) and const_cast<T>(x) as they make the intention more explicit. See : Stroustrup[^]

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

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

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