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. General Programming
  3. C#
  4. Explain this to me

Explain this to me

Scheduled Pinned Locked Moved C#
salesquestion
21 Posts 8 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.
  • R Rocky Moore

    There are somethings we are bound to miss, but I have a hard time beleiving, I missed this one. Did not pay attention to the usefulness of "AS"... Tanx! Rocky Moore <><

    I Offline
    I Offline
    Ista
    wrote on last edited by
    #10

    Well I kind of like the as even though it resembles vb code. I'm used to type casting in c++ where I constantly check for null values but I would much rather throw an exception. But then again exceptions in .NET are very costly and therefore as would work better. But then again if your not using reflection you should know what the object was and it would be easier to test for null. I guess would say the () is better in that it throws an exception unless it is a popular function in that case I would use as to keep it running fast. My opinion, critices and comments welcome nick I'm not an expert yet, but I play one at work. Yeah and here too.

    N J S A 4 Replies Last reply
    0
    • I Ista

      Well I kind of like the as even though it resembles vb code. I'm used to type casting in c++ where I constantly check for null values but I would much rather throw an exception. But then again exceptions in .NET are very costly and therefore as would work better. But then again if your not using reflection you should know what the object was and it would be easier to test for null. I guess would say the () is better in that it throws an exception unless it is a popular function in that case I would use as to keep it running fast. My opinion, critices and comments welcome nick I'm not an expert yet, but I play one at work. Yeah and here too.

      N Offline
      N Offline
      Nick Parker
      wrote on last edited by
      #11

      Ista wrote: I guess would say the () is better in that it throws an exception unless it is a popular function in that case I would use as to keep it running fast. Umm, the last part of your sentence does not make any sense, care to elaborate? Casting using "as" will not allow your code to run faster than standard casting mechanisms between types, if standard casting fails it will throw a InvalidCastException. If an "as" cast fails returning null and you access a method or property to your null object you will get a NullReferenceException. -Nick Parker

      I 1 Reply Last reply
      0
      • I Ista

        Well I kind of like the as even though it resembles vb code. I'm used to type casting in c++ where I constantly check for null values but I would much rather throw an exception. But then again exceptions in .NET are very costly and therefore as would work better. But then again if your not using reflection you should know what the object was and it would be easier to test for null. I guess would say the () is better in that it throws an exception unless it is a popular function in that case I would use as to keep it running fast. My opinion, critices and comments welcome nick I'm not an expert yet, but I play one at work. Yeah and here too.

        J Offline
        J Offline
        James T Johnson
        wrote on last edited by
        #12

        I use as when its possible for some object to not be castable to the type I want. For example:

        private void MyEventHandler(object sender, EventArgs e)
        {
        ToolBarButton b = sender as Button;
        MenuItem mi = sender as MenuItem;

        if( b != null )
        {
        // User clicked the toolbar button
        }
        else if( mi != null )
        {
        // User clicked the menu item or
        // used the shortcut keys
        }
        }

        You would so something like this where the same event handler is used for two different events. In this case standard behavior dictates (at least it used to) that when you click the Print button on the toolbar you don't show the Print dialog box. While clicking the Print command in the menu you should display the Print dialog box. Unfortunately my example has one slight flaw, the way the ToolBar control works makes it hard to use my example. I still chose to use that example because it is something we should be familiar with. You should use a cast when you don't expect the cast to fail (an exceptional condition calls for an exception to be thrown). James "I despise the city and much prefer being where a traffic jam means a line-up at McDonald's" Me when telling a friend why I wouldn't want to live with him

        I 1 Reply Last reply
        0
        • I Ista

          Well I kind of like the as even though it resembles vb code. I'm used to type casting in c++ where I constantly check for null values but I would much rather throw an exception. But then again exceptions in .NET are very costly and therefore as would work better. But then again if your not using reflection you should know what the object was and it would be easier to test for null. I guess would say the () is better in that it throws an exception unless it is a popular function in that case I would use as to keep it running fast. My opinion, critices and comments welcome nick I'm not an expert yet, but I play one at work. Yeah and here too.

          S Offline
          S Offline
          StealthyMark
          wrote on last edited by
          #13

          If the successful typecast is crucial in performing the function, go ahead and use var = (type) object;. If, however, there are alternate ways of performing the function, the as keyword is often better; even if you throw an exception anyway, because catching and rethrowing an exception is very expensive.

          void Function()
          {
          try
          {
          IReferenceService refSvc = (IReferenceService) GetService(typeof(IReferenceService));
          // do something
          }
          catch (Exception exc)
          {
          throw new UsefulException(message, exc);
          }
          }

          void Function()
          {
          IReferenceService refSvc = GetService(typeof(IReferenceService)) as IReferenceService;
          if (refSvc == null)
          {
          // alternatively, you could do it without refSvc
          throw new UsefulException(message);
          }
          // do something
          }

          1 Reply Last reply
          0
          • R Rocky Moore

            There are somethings we are bound to miss, but I have a hard time beleiving, I missed this one. Did not pay attention to the usefulness of "AS"... Tanx! Rocky Moore <><

            P Offline
            P Offline
            Philip Fitzsimons
            wrote on last edited by
            #14

            don't forget "IS" http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vclrfispg.asp[^]


            "When the only tool you have is a hammer, a sore thumb you will have."

            I 1 Reply Last reply
            0
            • N Nick Parker

              Ista wrote: I guess would say the () is better in that it throws an exception unless it is a popular function in that case I would use as to keep it running fast. Umm, the last part of your sentence does not make any sense, care to elaborate? Casting using "as" will not allow your code to run faster than standard casting mechanisms between types, if standard casting fails it will throw a InvalidCastException. If an "as" cast fails returning null and you access a method or property to your null object you will get a NullReferenceException. -Nick Parker

              I Offline
              I Offline
              Ista
              wrote on last edited by
              #15

              Well I guess I was misunderstanding in that I thought it would just return null instead of a casting exception. doh! I'm not an expert yet, but I play one at work. Yeah and here too.

              1 Reply Last reply
              0
              • J James T Johnson

                I use as when its possible for some object to not be castable to the type I want. For example:

                private void MyEventHandler(object sender, EventArgs e)
                {
                ToolBarButton b = sender as Button;
                MenuItem mi = sender as MenuItem;

                if( b != null )
                {
                // User clicked the toolbar button
                }
                else if( mi != null )
                {
                // User clicked the menu item or
                // used the shortcut keys
                }
                }

                You would so something like this where the same event handler is used for two different events. In this case standard behavior dictates (at least it used to) that when you click the Print button on the toolbar you don't show the Print dialog box. While clicking the Print command in the menu you should display the Print dialog box. Unfortunately my example has one slight flaw, the way the ToolBar control works makes it hard to use my example. I still chose to use that example because it is something we should be familiar with. You should use a cast when you don't expect the cast to fail (an exceptional condition calls for an exception to be thrown). James "I despise the city and much prefer being where a traffic jam means a line-up at McDonald's" Me when telling a friend why I wouldn't want to live with him

                I Offline
                I Offline
                Ista
                wrote on last edited by
                #16

                Okay so I am now totally confused Nick said if it cant cast to that type I get a cast exception. James says if it cant cast it just returns null. Well i guess I'll just test it myself, but in theory: C++: if cast to something thats not castable I get a null value(0), which is sweet then i just do an if an can ignore the horrible exception delay but if i cant I dont see what the difference is rather than code taste I'm not an expert yet, but I play one at work. Yeah and here too.

                N 1 Reply Last reply
                0
                • P Philip Fitzsimons

                  don't forget "IS" http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vclrfispg.asp[^]


                  "When the only tool you have is a hammer, a sore thumb you will have."

                  I Offline
                  I Offline
                  Ista
                  wrote on last edited by
                  #17

                  so actually if do an IS followed by an AS would be much faster if your not completely sure of the object I'm not an expert yet, but I play one at work. Yeah and here too.

                  1 Reply Last reply
                  0
                  • I Ista

                    Okay so I am now totally confused Nick said if it cant cast to that type I get a cast exception. James says if it cant cast it just returns null. Well i guess I'll just test it myself, but in theory: C++: if cast to something thats not castable I get a null value(0), which is sweet then i just do an if an can ignore the horrible exception delay but if i cant I dont see what the difference is rather than code taste I'm not an expert yet, but I play one at work. Yeah and here too.

                    N Offline
                    N Offline
                    Nick Parker
                    wrote on last edited by
                    #18

                    Ista wrote: Nick said if it cant cast to that type I get a cast exception. James says if it cant cast it just returns null I think you are confusing the two methods of casting we are talking about here. If you do something like:

                    Object o = new Something();
                    Something s = (Something)o;

                    and your cast fail, it will throw an InvalidCastException (Assuming Something is derived from Object). However if we are talking about an "as" casting and you doing something like:

                    Object o = new Object();
                    Something s = o as Something();
                    if(s != null)
                    {
                    //... use s here.
                    }

                    Failing to check if s is not equal to null and trying to access a member of s would throw an NullReferenceException if the cast for s was returned as null. -Nick Parker

                    I 1 Reply Last reply
                    0
                    • N Nick Parker

                      Ista wrote: Nick said if it cant cast to that type I get a cast exception. James says if it cant cast it just returns null I think you are confusing the two methods of casting we are talking about here. If you do something like:

                      Object o = new Something();
                      Something s = (Something)o;

                      and your cast fail, it will throw an InvalidCastException (Assuming Something is derived from Object). However if we are talking about an "as" casting and you doing something like:

                      Object o = new Object();
                      Something s = o as Something();
                      if(s != null)
                      {
                      //... use s here.
                      }

                      Failing to check if s is not equal to null and trying to access a member of s would throw an NullReferenceException if the cast for s was returned as null. -Nick Parker

                      I Offline
                      I Offline
                      Ista
                      wrote on last edited by
                      #19

                      I think it was the fact that I misunderstand or bypassed some of your answer. I have a bad habit of checking for null after I cast from the MFC days. I'm not an expert yet, but I play one at work. Yeah and here too.

                      1 Reply Last reply
                      0
                      • I Ista

                        Well I kind of like the as even though it resembles vb code. I'm used to type casting in c++ where I constantly check for null values but I would much rather throw an exception. But then again exceptions in .NET are very costly and therefore as would work better. But then again if your not using reflection you should know what the object was and it would be easier to test for null. I guess would say the () is better in that it throws an exception unless it is a popular function in that case I would use as to keep it running fast. My opinion, critices and comments welcome nick I'm not an expert yet, but I play one at work. Yeah and here too.

                        A Offline
                        A Offline
                        Arun Bhalla
                        wrote on last edited by
                        #20

                        Ista wrote: But then again exceptions in .NET are very costly and therefore as would work better. How costly are exceptions in .NET and why? I can see how excessively coding around exceptions would not be smart... but at least in ordinary C++, exceptions aren't really expensive, as far as I know.

                        I 1 Reply Last reply
                        0
                        • A Arun Bhalla

                          Ista wrote: But then again exceptions in .NET are very costly and therefore as would work better. How costly are exceptions in .NET and why? I can see how excessively coding around exceptions would not be smart... but at least in ordinary C++, exceptions aren't really expensive, as far as I know.

                          I Offline
                          I Offline
                          Ista
                          wrote on last edited by
                          #21

                          http://msdn.microsoft.com/vcsharp/using/understanding/perf/default.aspx?pull=/library/en-us/dndotnet/html/dotnetperftips.asp this is a link to one article. I spent 2 weeks going from link to link reading about how the CLR reacts and timing. This is a must read: http://msdn.microsoft.com/vcsharp/using/understanding/perf/default.aspx?pull=/library/en-us/dndotnet/html/fastmanagedcode.asp nick I'm not an expert yet, but I play one at work. Yeah and here too.

                          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