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

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

                                    E Offline
                                    E Offline
                                    Eusebiu Marcu
                                    wrote on last edited by
                                    #98

                                    There's a little more than that. See here: what-s-the-difference-between-as-and-cast-operators[^]

                                    Eusebiu

                                    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
                                      Amit Gupta AG
                                      wrote on last edited by
                                      #99

                                      'B' is better, Because use of 'as' operator does not throw exception if casting is not successful where as 'A' will throw exception in case casting fails.

                                      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

                                        D Offline
                                        D Offline
                                        Daniel Vaughan
                                        wrote on last edited by
                                        #100

                                        Often I see the 'as' keyword misused in a way that it hides the cause of a NullReferenceException. For example, take a look at this crummy code:

                                        ((foo as (Light)).SwitchOn(); // bad

                                        If foo is not a Light, then a NullReferenceException is raised. But if foo was null to begin with, then a NullReferenceException is also raised. In either case, we can’t be certain if it is one or the other. When the ‘as’ is replaced by a direct cast, an InvalidCastException is raised when foo is not a Light; allowing us to distinguish between the two situations:

                                        ((Light)foo).SwitchOn(); // better

                                        Sometimes, therefore, the choice to use 'as' or a direct cast isn’t a choice at all.

                                        Daniel Vaughan Twitter | Blog | Microsoft MVP | Projects: Calcium SDK, Clog | LinkedIn

                                        1 Reply Last reply
                                        0
                                        • N NormDroid

                                          For those using c#, what do you prefer? A.

                                          SomeObject obj = (SomeObject) e;

                                          or B.

                                          SomeObject obj = e as SomeObject;

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

                                          L Offline
                                          L Offline
                                          LucianPopescu
                                          wrote on last edited by
                                          #101

                                          I use this :

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

                                          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