Paul Gielens:ThoughtsService

another Endpoint to my thoughts

News

Syndication

Ads


Favorites

Projects

*Update, Dutch .NET Developers Alliance

One of my colleagues Peter Groenewegen has been added to the list. Check out his recipe for Sajoer Boerenkool, great for a team building meal ;) Peter also writes about the C# safe cast construction. Peter forgot the "is" variant. Which of the following options do you prefer? I choose #3 because it's execution is faster then option #1 and more explicit then option #2.

public class ReferenceTypeCastingDemo

{

       private class ACoolObject {}

 

 

       private class AnotherCoolObject {}

 

 

       public static void Main()

       {            

              ACoolObject instance = new ACoolObject();

              object cool = instance; // If only we had #pragma warning disable

              object anotherCool;

 

              // #1

              try

              {            

                     anotherCool = (AnotherCoolObject)cool;

              }

              catch (InvalidCastException ex)

              {

                     Console.WriteLine("Cool object blew in your face.");

              }

 

 

              // #2

              anotherCool = cool as AnotherCoolObject;

 

              if (anotherCool == null)

                     Console.WriteLine("Cool object blew in your face.");

 

      

              // #3

              anotherCool = cool;

 

              if (anotherCool is AnotherCoolObject)

                     Console.WriteLine("Some more cool code goes here...");

              else

                     Console.WriteLine("Cool object blew in your face.");

 

       }

}

Grab the OPML file here which contains allot of Dutch .Net developers. Are you a Dutch .Net developer and want your name on our list, drop a line pgielens@gmail.com

Posted: Nov 29 2004, 10:54 PM by p.gielens | with 5 comment(s)
Filed under:

Comments

No Comments