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

              G Offline
              G Offline
              Gary Wheeler
              wrote on last edited by
              #77

              As others have probably pointed out (but I'm too lazy to read the rest of the thread), the two versions do different things. 'A' throws an InvalidCastException if the cast isn't possible. 'B' sets obj to null if the cast doesn't work. Both are valid approaches, depending on the rest of your code.

              Software Zen: delete this;

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