C# equivalent to TryCast

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

    C# equivalent to TryCast

    Will somebody convert this for me...

    System.Web.UI.H tmlControls.Htm lHead header;
    header = TryCast(this.Pa ge.Header, System.Web.UI.H tmlControls.Htm lHead);

    <%= Clinton Gallagher
    NET csgallagher AT metromilwaukee. com
    URL http://clintongallagher.metromilwaukee.com/
    MAP http://wikimapia.org/#y=43038073&x=-...8&z=17&l=0&m=h


  • Dustin Campbell

    #2
    Re: C# equivalent to TryCast

    System.Web.UI.H tmlControls.Htm lHead header;
    header = this.Page.Heade r as System.Web.UI.H tmlControls.Htm lHead;
    if (header == null)
    // cast failed...
    else
    // cast succeeded...

    Best Regards,
    Dustin Campbell
    Developer Express Inc.


    Comment

    • clintonG

      #3
      Re: C# equivalent to TryCast

      Thanks...

      <%= Clinton

      "Dustin Campbell" <dustinc@no-spam-pleasedevexpres s.comwrote in message
      news:c155cb0e18 f988c8e0530b348 194@news.micros oft.com...
      System.Web.UI.H tmlControls.Htm lHead header;
      header = this.Page.Heade r as System.Web.UI.H tmlControls.Htm lHead;
      if (header == null)
      // cast failed...
      else
      // cast succeeded...
      >
      Best Regards,
      Dustin Campbell
      Developer Express Inc.
      >
      >

      Comment

      • nick.fletcher@iinet.net.au

        #4
        Re: C# equivalent to TryCast

        You can also use the "is" keyword

        System.Web.UI.H tmlControls.Htm lHead header;

        if (this.PageHeade r is System.Web.UI.H tmlControls.Htm lHead)
        {
        header = (this.PageHeade r as
        System.Web.UI.H tmlControls.Htm lHead);
        }

        On Nov 28, 7:58 am, "clintonG"
        <csgallag...@RE MOVETHISTEXTmet romilwaukee.com wrote:
        Thanks...
        >
        <%= Clinton
        >
        "Dustin Campbell" <dust...@no-spam-pleasedevexpres s.comwrote in messagenews:c15 5cb0e18f988c8e0 530b348194@news .microsoft.com. ..
        >
        System.Web.UI.H tmlControls.Htm lHead header;
        header = this.Page.Heade r as System.Web.UI.H tmlControls.Htm lHead;
        if (header == null)
        // cast failed...
        else
        // cast succeeded...
        >
        Best Regards,
        Dustin Campbell
        Developer Express Inc.

        Comment

        • Wiebe Tijsma

          #5
          Re: C# equivalent to TryCast


          This works fine as well, but I think the previous example has preference
          because it will only cast the object once.

          Wiebe Tijsma

          nick.fletcher@i inet.net.au wrote:
          You can also use the "is" keyword
          >
          System.Web.UI.H tmlControls.Htm lHead header;
          >
          if (this.PageHeade r is System.Web.UI.H tmlControls.Htm lHead)
          {
          header = (this.PageHeade r as
          System.Web.UI.H tmlControls.Htm lHead);
          }
          >
          On Nov 28, 7:58 am, "clintonG"
          <csgallag...@RE MOVETHISTEXTmet romilwaukee.com wrote:
          >Thanks...
          >>
          ><%= Clinton
          >>
          >"Dustin Campbell" <dust...@no-spam-pleasedevexpres s.comwrote in messagenews:c15 5cb0e18f988c8e0 530b348194@news .microsoft.com. ..
          >>
          >>System.Web.UI .HtmlControls.H tmlHead header;
          >>header = this.Page.Heade r as System.Web.UI.H tmlControls.Htm lHead;
          >>if (header == null)
          >> // cast failed...
          >>else
          >> // cast succeeded...
          >>Best Regards,
          >>Dustin Campbell
          >>Developer Express Inc.
          >

          Comment

          • Gabriel Lozano-MorĂ¡n

            #6
            Re: C# equivalent to TryCast

            I am just curious on why you want to cast at all?

            Gabriel Lozano-MorĂ¡n

            "clintonG" <csgallagher@RE MOVETHISTEXTmet romilwaukee.com wrote in message
            news:e5qS7VmEHH A.2312@TK2MSFTN GP02.phx.gbl...
            Will somebody convert this for me...
            >
            System.Web.UI.H tmlControls.Htm lHead header;
            header = TryCast(this.Pa ge.Header, System.Web.UI.H tmlControls.Htm lHead);
            >
            <%= Clinton Gallagher
            NET csgallagher AT metromilwaukee. com
            URL http://clintongallagher.metromilwaukee.com/
            MAP http://wikimapia.org/#y=43038073&x=-...8&z=17&l=0&m=h
            >

            Comment

            • clintonG

              #7
              Re: C# equivalent to TryCast

              Can somebody explain why this cast and this form of cast is used?

              // An object named header is derived (?) from the class HtmlHead
              System.Web.UI.H tmlControls.Htm lHead header;

              // Using the is keyword this instance of the PageHeader object is typed
              // as an HtmlHead object allowing the instance of this.PageHeader object
              // to "borrow" properties of an HtmlHead object
              this.PageHeader is System.Web.UI.H tmlControls.Htm lHead

              I read the "is a" and the "has a" relationship but I don't understand
              the "why a" and this is where I burn out.


              <%= Clinton Gallagher


              "Wiebe Tijsma" <wiebeREMOVE@CA PITALStijsma.co mwrote in message
              news:%238PMgdoE HHA.4508@TK2MSF TNGP02.phx.gbl. ..
              >
              This works fine as well, but I think the previous example has preference
              because it will only cast the object once.
              >
              Wiebe Tijsma
              >
              nick.fletcher@i inet.net.au wrote:
              >You can also use the "is" keyword
              >>
              >System.Web.UI. HtmlControls.Ht mlHead header;
              >>
              >if (this.PageHeade r is System.Web.UI.H tmlControls.Htm lHead)
              >{
              > header = (this.PageHeade r as
              >System.Web.UI. HtmlControls.Ht mlHead);
              >}
              >>
              >On Nov 28, 7:58 am, "clintonG"
              ><csgallag...@R EMOVETHISTEXTme tromilwaukee.co mwrote:
              >>Thanks...
              >>>
              >><%= Clinton
              >>>
              >>"Dustin Campbell" <dust...@no-spam-pleasedevexpres s.comwrote in
              >>messagenews:c 155cb0e18f988c8 e0530b348194@ne ws.microsoft.co m...
              >>>
              >>>System.Web.U I.HtmlControls. HtmlHead header;
              >>>header = this.Page.Heade r as System.Web.UI.H tmlControls.Htm lHead;
              >>>if (header == null)
              >>> // cast failed...
              >>>else
              >>> // cast succeeded...
              >>>Best Regards,
              >>>Dustin Campbell
              >>>Developer Express Inc.
              >>

              Comment

              • nick.fletcher@iinet.net.au

                #8
                Re: C# equivalent to TryCast

                In fact - the compiled msil is exactly the same but the example which
                doesnt use "is" makes one extra read and write to the stack (tho not
                being an expert in reading msil I couldnt tell you why)

                try it :-)

                On Nov 28, 11:51 am, Wiebe Tijsma <wiebeREM...@CA PITALStijsma.co m>
                wrote:
                This works fine as well, but I think the previous example has preference
                because it will only cast the object once.
                >
                Wiebe Tijsma
                >
                nick.fletc...@i inet.net.au wrote:
                You can also use the "is" keyword
                >
                System.Web.UI.H tmlControls.Htm lHead header;
                >
                if (this.PageHeade r is System.Web.UI.H tmlControls.Htm lHead)
                {
                header = (this.PageHeade r as
                System.Web.UI.H tmlControls.Htm lHead);
                }
                >
                On Nov 28, 7:58 am, "clintonG"
                <csgallag...@RE MOVETHISTEXTmet romilwaukee.com wrote:
                Thanks...
                >
                <%= Clinton
                >
                "Dustin Campbell" <dust...@no-spam-pleasedevexpres s.comwrote in messagenews:c15 5cb0e18f988c8e0 530b348194@news .microsoft.com. ..
                >
                >System.Web.UI. HtmlControls.Ht mlHead header;
                >header = this.Page.Heade r as System.Web.UI.H tmlControls.Htm lHead;
                >if (header == null)
                > // cast failed...
                >else
                > // cast succeeded...
                >Best Regards,
                >Dustin Campbell
                >Developer Express Inc.

                Comment

                • clintonG

                  #9
                  Re: C# equivalent to TryCast

                  I found the code in VB while trying to learn what options were available to
                  me to write into the head of the page when using Themes. I need to control
                  writing linked style sheets *after* the link element generated by the Theme.

                  <%= Clinton Gallagher

                  "Gabriel Lozano-MorĂ¡n" <abuse@frontbri dge.comwrote in message
                  news:%23KUcseoE HHA.5028@TK2MSF TNGP03.phx.gbl. ..
                  >I am just curious on why you want to cast at all?
                  >
                  Gabriel Lozano-MorĂ¡n
                  >
                  "clintonG" <csgallagher@RE MOVETHISTEXTmet romilwaukee.com wrote in message
                  news:e5qS7VmEHH A.2312@TK2MSFTN GP02.phx.gbl...
                  >Will somebody convert this for me...
                  >>
                  >System.Web.UI. HtmlControls.Ht mlHead header;
                  >header = TryCast(this.Pa ge.Header, System.Web.UI.H tmlControls.Htm lHead);
                  >>
                  ><%= Clinton Gallagher
                  > NET csgallagher AT metromilwaukee. com
                  > URL http://clintongallagher.metromilwaukee.com/
                  > MAP http://wikimapia.org/#y=43038073&x=-...8&z=17&l=0&m=h
                  >>
                  >
                  >

                  Comment

                  • clintonG

                    #10
                    Re: C# equivalent to TryCast

                    I picked up the code snippet from Accessing the Html Header in ASP.NET 2.0
                    [1]. I'm trying to make sense of how to use it when using Themes.

                    <%= Clinton Gallagher

                    [1] http://weblogs.asp.net/pscott/archiv...30/424039.aspx

                    "clintonG" <csgallagher@RE MOVETHISTEXTmet romilwaukee.com wrote in message
                    news:%23khKBXpE HHA.1196@TK2MSF TNGP02.phx.gbl. ..
                    >I found the code in VB while trying to learn what options were available to
                    >me to write into the head of the page when using Themes. I need to control
                    >writing linked style sheets *after* the link element generated by the
                    >Theme.
                    >
                    <%= Clinton Gallagher
                    >
                    "Gabriel Lozano-MorĂ¡n" <abuse@frontbri dge.comwrote in message
                    news:%23KUcseoE HHA.5028@TK2MSF TNGP03.phx.gbl. ..
                    >>I am just curious on why you want to cast at all?
                    >>
                    >Gabriel Lozano-MorĂ¡n
                    >>
                    >"clintonG" <csgallagher@RE MOVETHISTEXTmet romilwaukee.com wrote in
                    >message news:e5qS7VmEHH A.2312@TK2MSFTN GP02.phx.gbl...
                    >>Will somebody convert this for me...
                    >>>
                    >>System.Web.UI .HtmlControls.H tmlHead header;
                    >>header = TryCast(this.Pa ge.Header, System.Web.UI.H tmlControls.Htm lHead);
                    >>>
                    >><%= Clinton Gallagher
                    >> NET csgallagher AT metromilwaukee. com
                    >> URL http://clintongallagher.metromilwaukee.com/
                    >> MAP http://wikimapia.org/#y=43038073&x=-...8&z=17&l=0&m=h
                    >>>
                    >>
                    >>
                    >
                    >

                    Comment

                    • Dustin Campbell

                      #11
                      Re: C# equivalent to TryCast

                      In fact - the compiled msil is exactly the same but the example which
                      doesnt use "is" makes one extra read and write to the stack (tho not
                      being an expert in reading msil I couldnt tell you why)
                      >
                      try it :-)
                      Actually that's not true at all. See http://www.boyet.com/Articles/Double...tiPattern.html
                      for details. I compiled the example code at that blog entry and got the following
                      results:

                      class Program
                      {
                      class Foo
                      {
                      public int Length { get { return 0; } }
                      }

                      static int DoubleCast(obje ct obj)
                      {
                      if (obj is Foo)
                      return ((Foo)obj).Leng th;

                      return -1;
                      }
                      static int SingleCast(obje ct obj)
                      {
                      Foo foo = obj as Foo;
                      if (foo != null)
                      return foo.Length;

                      return -1;
                      }

                      static void Main(string[] args) { }
                      }

                      DoubleCast compiles to this IL:

                      ..method private hidebysig static int32 DoubleCast(obje ct obj) cil managed
                      {
                      .maxstack 8
                      L_0000: ldarg.0
                      L_0001: isinst CastTest.Progra m/Foo
                      L_0006: brfalse.s L_0014
                      L_0008: ldarg.0
                      L_0009: castclass CastTest.Progra m/Foo
                      L_000e: callvirt instance int32 CastTest.Progra m/Foo::get_Length ()
                      L_0013: ret
                      L_0014: ldc.i4.m1
                      L_0015: ret
                      }

                      and SingleCast compiles to this:

                      ..method private hidebysig static int32 SingleCast(obje ct obj) cil managed
                      {
                      .maxstack 1
                      .locals init (
                      [0] CastTest.Progra m/Foo foo)
                      L_0000: ldarg.0
                      L_0001: isinst CastTest.Progra m/Foo
                      L_0006: stloc.0
                      L_0007: ldloc.0
                      L_0008: brfalse.s L_0011
                      L_000a: ldloc.0
                      L_000b: callvirt instance int32 CastTest.Progra m/Foo::get_Length ()
                      L_0010: ret
                      L_0011: ldc.i4.m1
                      L_0012: ret
                      }

                      The differeince is the additional "castclass" in DoubleCast at L_0012. This
                      actually results in two "castclass" operations if you consider the definition
                      of the "isinst" instruction that appears L_0002:

                      "isinst <token(0x75). Check to see whether the object reference on the
                      stack is an instance of the class specified by <token>. <tokenmust be a
                      valid TypeDef, TypeRef, or TypeSpec token. This instruction takes the object
                      reference from the stack and pushes the result on the stack. If the check
                      succeeds, the result is an object reference, **as if castclass had been invoked**;
                      otherwise, the result is a null reference, as if ldnull had been invoked."
                      - Expert .NET 2.0 IL Assembler by Serge Lidin, pg. 287 (emphasis mine)

                      So, in the first example, the IL is not all that optimal because the result
                      of the "isinst" instruction is compared against null and thrown away -- only
                      to be recalculated later from the parameter by the "castclass" instruction.
                      In the second example, the result of the *isinst" instruction is copied to
                      a local so there isn't any need for "castclass" .

                      Best Regards,
                      Dustin Campbell
                      Developer Express Inc.



                      Comment

                      • Dave Sexton

                        #12
                        Re: C# equivalent to TryCast

                        Hi Dustin,

                        Interesting stuff.

                        If you run VS 2005 Code Analysis on the sample code you'll see a warning
                        about double-casting. It's one of the more annoying warnings produced, IMO.

                        "Do not cast unnecessarily (CA1800)"


                        Personally, I prefer the code in DoubleCast and I'm not really worried about
                        any negative impact it may have on performance, normally.

                        (On a side note, I'd just like to vent a bit: MSDN is terribly slow right
                        now and it's driving me crazy :)

                        --
                        Dave Sexton

                        "Dustin Campbell" <dustinc@no-spam-pleasedevexpres s.comwrote in message
                        news:c155cb0e19 13d8c8e0ea1359f 9ac@news.micros oft.com...
                        >In fact - the compiled msil is exactly the same but the example which
                        >doesnt use "is" makes one extra read and write to the stack (tho not
                        >being an expert in reading msil I couldnt tell you why)
                        >>
                        >try it :-)
                        >
                        Actually that's not true at all. See
                        http://www.boyet.com/Articles/Double...tiPattern.html for details. I
                        compiled the example code at that blog entry and got the following
                        results:
                        >
                        class Program
                        {
                        class Foo
                        {
                        public int Length { get { return 0; } }
                        }
                        >
                        static int DoubleCast(obje ct obj)
                        {
                        if (obj is Foo)
                        return ((Foo)obj).Leng th;
                        >
                        return -1;
                        }
                        static int SingleCast(obje ct obj)
                        {
                        Foo foo = obj as Foo;
                        if (foo != null)
                        return foo.Length;
                        >
                        return -1;
                        }
                        >
                        static void Main(string[] args) { }
                        }
                        >
                        DoubleCast compiles to this IL:
                        >
                        .method private hidebysig static int32 DoubleCast(obje ct obj) cil managed
                        {
                        .maxstack 8
                        L_0000: ldarg.0 L_0001: isinst CastTest.Progra m/Foo
                        L_0006: brfalse.s L_0014
                        L_0008: ldarg.0 L_0009: castclass CastTest.Progra m/Foo
                        L_000e: callvirt instance int32 CastTest.Progra m/Foo::get_Length ()
                        L_0013: ret L_0014: ldc.i4.m1 L_0015: ret }
                        >
                        and SingleCast compiles to this:
                        >
                        .method private hidebysig static int32 SingleCast(obje ct obj) cil managed
                        {
                        .maxstack 1
                        .locals init (
                        [0] CastTest.Progra m/Foo foo)
                        L_0000: ldarg.0 L_0001: isinst CastTest.Progra m/Foo
                        L_0006: stloc.0 L_0007: ldloc.0 L_0008: brfalse.s L_0011
                        L_000a: ldloc.0 L_000b: callvirt instance int32
                        CastTest.Progra m/Foo::get_Length ()
                        L_0010: ret L_0011: ldc.i4.m1 L_0012: ret }
                        >
                        The differeince is the additional "castclass" in DoubleCast at L_0012.
                        This actually results in two "castclass" operations if you consider the
                        definition of the "isinst" instruction that appears L_0002:
                        >
                        "isinst <token(0x75). Check to see whether the object reference on the
                        stack is an instance of the class specified by <token>. <tokenmust be a
                        valid TypeDef, TypeRef, or TypeSpec token. This instruction takes the
                        object reference from the stack and pushes the result on the stack. If the
                        check succeeds, the result is an object reference, **as if castclass had
                        been invoked**; otherwise, the result is a null reference, as if ldnull
                        had been invoked." - Expert .NET 2.0 IL Assembler by Serge Lidin, pg. 287
                        (emphasis mine)
                        >
                        So, in the first example, the IL is not all that optimal because the
                        result of the "isinst" instruction is compared against null and thrown
                        away -- only to be recalculated later from the parameter by the
                        "castclass" instruction. In the second example, the result of the *isinst"
                        instruction is copied to a local so there isn't any need for "castclass" .
                        >
                        Best Regards,
                        Dustin Campbell
                        Developer Express Inc.
                        >
                        >
                        >

                        Comment

                        • Dustin Campbell

                          #13
                          Re: C# equivalent to TryCast

                          "Do not cast unnecessarily (CA1800)"

                          Personally, I prefer the code in DoubleCast and I'm not really worried
                          about any negative impact it may have on performance, normally.
                          Just as long as you know that the problem is there. I mean, I haven't stopped
                          using foreach just because it's inefficient in comparisan to say Array.ForEach,
                          List.ForEach or a hard-coded for or while loop.

                          Best Regards,
                          Dustin Campbell
                          Developer Express Inc.


                          Comment

                          • Dave Sexton

                            #14
                            Re: C# equivalent to TryCast

                            Hi Dustin,

                            Agreed.

                            --
                            Dave Sexton

                            "Dustin Campbell" <dustinc@no-spam-pleasedevexpres s.comwrote in message
                            news:c155cb0e19 1d88c8e108c52e4 8cc@news.micros oft.com...
                            >"Do not cast unnecessarily (CA1800)"
                            >http://msdn2.microsoft.com/en-us/lib...71(vs.80).aspx
                            >Personally, I prefer the code in DoubleCast and I'm not really worried
                            >about any negative impact it may have on performance, normally.
                            >
                            Just as long as you know that the problem is there. I mean, I haven't
                            stopped using foreach just because it's inefficient in comparisan to say
                            Array.ForEach, List.ForEach or a hard-coded for or while loop.
                            >
                            Best Regards,
                            Dustin Campbell
                            Developer Express Inc.
                            >
                            >

                            Comment

                            • Dave Sexton

                              #15
                              Re: C# equivalent to TryCast

                              Hi,
                              Can somebody explain why this cast and this form of cast is used?
                              "is" is a binary operator used to check whether a variable "is" of the
                              specified type or a derived-type. It's commonly used as a predicate in an
                              "if" statement. "is" does not perform a cast that can be assigned to a
                              variable.

                              "as" is a binary operator used to coerce a variable into the specified
                              reference-type or null if the variable is null or the instance is not of the
                              specified reference-type or a derived-type. "as" performs a cast that can
                              be assigned to a variable.

                              Without the use of "is" and "as" you'd have to use reflection or attempt an
                              explicit cast, catching InvalidCastExce ption.
                              // An object named header is derived (?) from the class HtmlHead
                              System.Web.UI.H tmlControls.Htm lHead header;
                              In your example a variable named header is typed as HtmlHead. You could
                              even say that, "header is an instance of HtmlHead", unless of course it's a
                              null reference, but "derived" is not the appropriate word to use here.
                              // Using the is keyword this instance of the PageHeader object is typed
                              // as an HtmlHead object allowing the instance of this.PageHeader object
                              // to "borrow" properties of an HtmlHead object
                              this.PageHeader is System.Web.UI.H tmlControls.Htm lHead
                              The "is" operator returns either true or false. It's used as a comparison,
                              not for assignment.

                              In your example, if the PageHeader property returns an instance of an object
                              that is of the type, "HtmlHead" or a derived type, then the entire "is"
                              expression will return true, otherwise false:

                              bool isHtmlHead = this.PageHeader is HtmlHead;

                              The "as" operator returns the result of the coercion. When the argument
                              being tested is not null and is of the specified type or a derived type, a
                              non-null reference will be returned, otherwise null will be returned:

                              HtmlHead header = this.PageHeader as HtmlHead;

                              if (header != null)
                              Trace.WriteLine ("PageHeader is an instance of HtmlHead or a derived
                              type");
                              else
                              Trace.WriteLine ("PageHeader is null or not an instance of HtmlHead or a
                              derived type");
                              I read the "is a" and the "has a" relationship but I don't understand
                              the "why a" and this is where I burn out.
                              You got me here - care to clarify this statement?

                              --
                              Dave Sexton


                              Comment

                              Working...