Up casting (base to derived) in C#

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Mark Wilden

    #16
    Re: Up casting (base to derived) in C#

    "Jon Skeet [C# MVP]" <skeet@pobox.co mwrote in message
    news:MPG.1f324c eb2ddaf65c98d34 d@msnews.micros oft.com...
    Upcasting is the (almost always
    unnecessary) casting from the derived class to the base class.
    How "almost"? (I have the unpleasant feeling that I'm about to learn
    something.)

    ///ark


    Comment

    • Jon Skeet [C# MVP]

      #17
      Re: Up casting (base to derived) in C#

      Mark Wilden <MarkWilden@new sgroups.nospamw rote:
      "Jon Skeet [C# MVP]" <skeet@pobox.co mwrote in message
      news:MPG.1f324c eb2ddaf65c98d34 d@msnews.micros oft.com...
      >
      Upcasting is the (almost always
      unnecessary) casting from the derived class to the base class.
      >
      How "almost"? (I have the unpleasant feeling that I'm about to learn
      something.)
      You sometimes need to cast in order to pick the right overload. For
      instance:

      using System;

      class Test
      {
      static void Main()
      {
      string x = "hello";
      Foo(x);
      Foo((object)x);
      }

      static void Foo(string x)
      {
      Console.WriteLi ne ("Foo(string)") ;
      }

      static void Foo(object o)
      {
      Console.WriteLi ne ("Foo(object)") ;
      }
      }

      --
      Jon Skeet - <skeet@pobox.co m>
      http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
      If replying to the group, please do not mail me too

      Comment

      • Sericinus hunter

        #18
        Re: Up casting (base to derived) in C#

        Mark Wilden wrote:
        "Jon Skeet [C# MVP]" <skeet@pobox.co mwrote in message
        news:MPG.1f324c eb2ddaf65c98d34 d@msnews.micros oft.com...
        >
        >Upcasting is the (almost always
        >unnecessary) casting from the derived class to the base class.
        >
        How "almost"? (I have the unpleasant feeling that I'm about to learn
        something.)
        To my understanding, using this construct
        ((BaseClass)ins tanceOfDerivedC lass).Method() you will call base class
        implementation of Method(), given it is not virtual and overridden
        in the derived class.

        Comment

        • Tigger

          #19
          Re: Up casting (base to derived) in C#

          Dont forget that you can also use the is keyword:

          if (obj is MyType)
          {
          MyType myObject = (MyType)obj;
          // do my thing
          }

          I also believe casting can return null (if supplied with null) so error
          checking is also needed if you cast (except above where you pre-check
          its safe)

          Tony

          Comment

          • Shawn Wildermuth (C# MVP)

            #20
            Re: Up casting (base to derived) in C#

            Hello Tigger,

            Almost always the better pattern is to try the cast with the "as" operator:

            MyType myObject = obj as MyType;
            if (myObject != null)
            {
            // do my thing
            }

            This is more efficient (and in my opinion is more direct to read).

            Thanks,
            Shawn Wildermuth
            Speaker, Author and C# MVP

            Dont forget that you can also use the is keyword:
            >
            if (obj is MyType)
            {
            MyType myObject = (MyType)obj;
            // do my thing
            }
            I also believe casting can return null (if supplied with null) so
            error checking is also needed if you cast (except above where you
            pre-check its safe)
            >
            Tony
            >

            Comment

            • Tigger

              #21
              Re: Up casting (base to derived) in C#

              Hi Shawn,

              I would have thought the "is" would be more efficient than the "as"
              plus null check?

              I guess if normal flow is for it to pass the null check then the
              argument is if an "is" plus cast is slower than an "as" plus null
              check. Which I would guess to be the case. So in those scenarios it
              would be faster to do it your way.

              I tend to use the pattern as a kind of switch statement

              if (obj is AType)
              {
              AType aType = (AType)obj;
              // do atype special things
              }
              else if (obj is BType)
              {
              BType bType = (BType)obj;
              // do btype things
              }

              With this scenario its not the most readable but in my opinion it is
              slightly easier to read than using "as"s and null checks.

              Of course I try to avoid doing this sort of thing by using interfaces,
              inheritance, strong typing, generics etc.

              Tigger

              Shawn Wildermuth (C# MVP) wrote:
              Hello Tigger,
              >
              Almost always the better pattern is to try the cast with the "as" operator:
              >
              MyType myObject = obj as MyType;
              if (myObject != null)
              {
              // do my thing
              }
              >
              This is more efficient (and in my opinion is more direct to read).
              >
              Thanks,
              Shawn Wildermuth
              Speaker, Author and C# MVP

              >
              Dont forget that you can also use the is keyword:

              if (obj is MyType)
              {
              MyType myObject = (MyType)obj;
              // do my thing
              }
              I also believe casting can return null (if supplied with null) so
              error checking is also needed if you cast (except above where you
              pre-check its safe)

              Tony

              Comment

              • Jon Skeet [C# MVP]

                #22
                Re: Up casting (base to derived) in C#

                Tigger <tony@grunt.tvw rote:
                I would have thought the "is" would be more efficient than the "as"
                plus null check?
                No. "is", "as" and a cast all do pretty much the same thing, and that
                thing is more expensive than a null check. Therefore is+cast is more
                expensive than as+null check.

                --
                Jon Skeet - <skeet@pobox.co m>
                http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
                If replying to the group, please do not mail me too

                Comment

                • Tigger

                  #23
                  Re: Up casting (base to derived) in C#

                  Which is what I said later.

                  However an "is" is more efficient than an as+null check so if the ratio
                  of matches is low it is better to use "is"s and if the ratio is high
                  use as+null checks

                  If you are doing multiple checks like my example its most likely the
                  list of "is"s plus a single cast (when matched) will be more efficient
                  than a list of as+null checks.

                  Theres probably a break even point, say 5 ;-)

                  Tigger


                  Jon wrote:
                  Tigger <tony@grunt.tvw rote:
                  I would have thought the "is" would be more efficient than the "as"
                  plus null check?
                  >
                  No. "is", "as" and a cast all do pretty much the same thing, and that
                  thing is more expensive than a null check. Therefore is+cast is more
                  expensive than as+null check.
                  >
                  --
                  Jon Skeet - <skeet@pobox.co m>
                  http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
                  If replying to the group, please do not mail me too

                  Comment

                  • Jon Skeet [C# MVP]

                    #24
                    Re: Up casting (base to derived) in C#

                    Tigger <tony@grunt.tvw rote:
                    Which is what I said later.
                    >
                    However an "is" is more efficient than an as+null check so if the ratio
                    of matches is low it is better to use "is"s and if the ratio is high
                    use as+null checks
                    >
                    If you are doing multiple checks like my example its most likely the
                    list of "is"s plus a single cast (when matched) will be more efficient
                    than a list of as+null checks.
                    "is" *is* an as+null check, in fact. In IL, "is" compiles to:
                    IL_0007: ldloc.0
                    IL_0008: isinst [mscorlib]System.String
                    IL_000d: ldnull
                    IL_000e: cgt.un
                    IL_0010: ldc.i4.0
                    IL_0011: ceq
                    IL_0013: stloc.1
                    IL_0014: ldloc.1
                    IL_0015: brtrue.s IL_0024

                    "as Stream != null" compiles to:
                    IL_0024: ldloc.0
                    IL_0025: isinst [mscorlib]System.IO.Strea m
                    IL_002a: ldnull
                    IL_002b: ceq
                    IL_002d: stloc.1
                    IL_002e: ldloc.1
                    IL_002f: brtrue.s IL_003e

                    I'm not sure what there's the additional cgt.un in the "is" case, but I
                    doubt that it gets as far as the generated native code...
                    Theres probably a break even point, say 5 ;-)
                    Is it fair to assume that you pulled that number out of thin air?

                    --
                    Jon Skeet - <skeet@pobox.co m>
                    http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
                    If replying to the group, please do not mail me too

                    Comment

                    • Tigger

                      #25
                      Re: Up casting (base to derived) in C#

                      Ah,

                      So if "is" is equivalent to an as+null check then it would be best to
                      do as+null checks and skip the need for a cast.

                      I was working on "is" being equal to an "as" as you stated in an
                      earlier post.

                      I stand corrected.

                      5 seemed a good random number, I did indicate that though.

                      Tigger

                      Jon wrote:
                      Tigger <tony@grunt.tvw rote:
                      Which is what I said later.

                      However an "is" is more efficient than an as+null check so if the ratio
                      of matches is low it is better to use "is"s and if the ratio is high
                      use as+null checks

                      If you are doing multiple checks like my example its most likely the
                      list of "is"s plus a single cast (when matched) will be more efficient
                      than a list of as+null checks.
                      >
                      "is" *is* an as+null check, in fact. In IL, "is" compiles to:
                      IL_0007: ldloc.0
                      IL_0008: isinst [mscorlib]System.String
                      IL_000d: ldnull
                      IL_000e: cgt.un
                      IL_0010: ldc.i4.0
                      IL_0011: ceq
                      IL_0013: stloc.1
                      IL_0014: ldloc.1
                      IL_0015: brtrue.s IL_0024
                      >
                      "as Stream != null" compiles to:
                      IL_0024: ldloc.0
                      IL_0025: isinst [mscorlib]System.IO.Strea m
                      IL_002a: ldnull
                      IL_002b: ceq
                      IL_002d: stloc.1
                      IL_002e: ldloc.1
                      IL_002f: brtrue.s IL_003e
                      >
                      I'm not sure what there's the additional cgt.un in the "is" case, but I
                      doubt that it gets as far as the generated native code...
                      >
                      Theres probably a break even point, say 5 ;-)
                      >
                      Is it fair to assume that you pulled that number out of thin air?
                      >
                      --
                      Jon Skeet - <skeet@pobox.co m>
                      http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
                      If replying to the group, please do not mail me too

                      Comment

                      Working...