Casting using "as" question

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

    #1

    Casting using "as" question

    What is the benefit of using "as" vs the other?

    HttpWebRequest myReq
    = (HttpWebRequest )WebRequest.Cre ate("http://www.contoso.com/");

    vs.

    HttpWebRequest myReq = WebRequest.Crea te("http://www.contoso.com/") as
    HttpWebRequest;

    Based on the MS documenation "The as operator is like a cast except that it
    yields null on conversion failure instead of raising an exception. "

    I've read some internal coding standards that state "Use the as operator to
    defensively cast to a type", but I don't quite get the benefit of this and
    want an outside opinion.

    Thanks.

  • Angel J. Hernández M.

    #2
    Re: Casting using "as&quo t; question

    It returns an object of the resulting cast (if successful) or null. So you
    can use the object afterwards and it doesn't raise an exception (just like
    the MS documentation states).

    Best regards,


    --
    Angel J. Hernández M.
    MCP - MCAD - MCSD - MCDBA
    Microsoft MVP ASP/ASP.NET

    Impulse su empresa con soluciones expertas en ciberseguridad, automatización de procesos y licenciamiento Microsoft corporativo con Consein.






    "Dave" <Dave@discussio ns.microsoft.co m> wrote in message
    news:F656E135-D958-4E13-9DA7-EC6EF79F6C63@mi crosoft.com...[color=blue]
    > What is the benefit of using "as" vs the other?
    >
    > HttpWebRequest myReq
    > = (HttpWebRequest )WebRequest.Cre ate("http://www.contoso.com/");
    >
    > vs.
    >
    > HttpWebRequest myReq = WebRequest.Crea te("http://www.contoso.com/") as
    > HttpWebRequest;
    >
    > Based on the MS documenation "The as operator is like a cast except that
    > it
    > yields null on conversion failure instead of raising an exception. "
    >
    > I've read some internal coding standards that state "Use the as operator
    > to
    > defensively cast to a type", but I don't quite get the benefit of this and
    > want an outside opinion.
    >
    > Thanks.
    >[/color]


    Comment

    • Thaddaeus Parker

      #3
      Re: Casting using &quot;as&quo t; question

      Using "as" allows for the "graceful" failure of casting one object to
      another.
      As per your examples:[color=blue]
      > HttpWebRequest myReq
      > = (HttpWebRequest )WebRequest.Cre ate("http://www.contoso.com/"); --This
      > will cause an exception of InvalidCastExce ption if the system can cast the
      > web request as a httpwebrequest. But if we were to use "as"
      >
      > vs.
      >
      > HttpWebRequest myReq = WebRequest.Crea te("http://www.contoso.com/") as
      > HttpWebRequest; -- this will capture the possible exception and return a
      > null allowing for your code to be execute as normal.[/color]

      Think of "as" as being
      public static void as(ref object a, object b, Type someType){
      try{
      a = (someType)b;
      }catch{ a = null;}
      }
      }
      In some cases using "as" is much safer than attempting to forceably cast one
      type to another type.

      Thaddaeus

      "Dave" <Dave@discussio ns.microsoft.co m> wrote in message
      news:F656E135-D958-4E13-9DA7-EC6EF79F6C63@mi crosoft.com...[color=blue]
      > What is the benefit of using "as" vs the other?
      >
      > HttpWebRequest myReq
      > = (HttpWebRequest )WebRequest.Cre ate("http://www.contoso.com/");
      >
      > vs.
      >
      > HttpWebRequest myReq = WebRequest.Crea te("http://www.contoso.com/") as
      > HttpWebRequest;
      >
      > Based on the MS documenation "The as operator is like a cast except that
      > it
      > yields null on conversion failure instead of raising an exception. "
      >
      > I've read some internal coding standards that state "Use the as operator
      > to
      > defensively cast to a type", but I don't quite get the benefit of this and
      > want an outside opinion.
      >
      > Thanks.
      >[/color]


      Comment

      • Hans Kesting

        #4
        Re: Casting using &quot;as&quo t; question

        > What is the benefit of using "as" vs the other?[color=blue]
        >
        > HttpWebRequest myReq
        > = (HttpWebRequest )WebRequest.Cre ate("http://www.contoso.com/");
        >
        > vs.
        >
        > HttpWebRequest myReq = WebRequest.Crea te("http://www.contoso.com/") as
        > HttpWebRequest;
        >
        > Based on the MS documenation "The as operator is like a cast except that it
        > yields null on conversion failure instead of raising an exception. "
        >
        > I've read some internal coding standards that state "Use the as operator to
        > defensively cast to a type", but I don't quite get the benefit of this and
        > want an outside opinion.
        >
        > Thanks.[/color]

        And an extra remark:

        unlike a direct cast, you can't use "as" on value types
        ("theobj as int"), because it can return null, which value-types can't
        handle.

        Hans Kesting


        Comment

        • Jon Skeet [C# MVP]

          #5
          Re: Casting using &quot;as&quo t; question

          Hans Kesting wrote:
          [color=blue]
          > And an extra remark:
          >
          > unlike a direct cast, you can't use "as" on value types
          > ("theobj as int"), because it can return null, which value-types can't
          > handle.[/color]

          That's not strictly true under .NET 2.0. Nullable<T> types are still
          value types, but can be used with "as":

          using System;

          class Test
          {
          static void Main()
          {
          object o = 5;
          int? x = o as int?;
          }
          }

          (Note that if you remove the last ? in the program, you'll get a
          compiler error CS0077 which has an inaccurate description - I've
          reported it to MS).

          Jon

          Comment

          • John Murray

            #6
            Re: Casting using &quot;as&quo t; question

            Internally, they are two different CIL instructions -- castclass
            (straight cast) and isinst (as.) The primary difference, as noted
            already is that the castclass instruction generates an exception when no
            cast exists while the isinst just places a null value on the evaluation
            stack.

            The implication is that if you know -- or expect your type to always be
            castable then the castclass instruction provides some runtime safety in
            case an unexpected value comes through -- and you dont suffer the
            penalty of spinning up an exception. If, on the other hand, you are not
            sure what the type will be, and you want to handle it gracefully, then
            isinst allows you to avoid the performance penalties of an exception if
            the class cannot be cast.



            Dave wrote:[color=blue]
            > What is the benefit of using "as" vs the other?
            >
            > HttpWebRequest myReq
            > = (HttpWebRequest )WebRequest.Cre ate("http://www.contoso.com/");
            >
            > vs.
            >
            > HttpWebRequest myReq = WebRequest.Crea te("http://www.contoso.com/") as
            > HttpWebRequest;
            >
            > Based on the MS documenation "The as operator is like a cast except that it
            > yields null on conversion failure instead of raising an exception. "
            >
            > I've read some internal coding standards that state "Use the as operator to
            > defensively cast to a type", but I don't quite get the benefit of this and
            > want an outside opinion.
            >
            > Thanks.
            >[/color]

            Comment

            Working...