Tuesday, June 22, 2010

C# tip - 6/22/2010

Advantages and disadvantages of is, as, and cast operations.

is - used to checked whether an object is a specific type
Object t;
if(t is SomeType){...}
  • Advantages
    • checks an object without an overhead of a try/catch block
  • Disadvantages
    • doesn't actually cast anything
as - used to cast reference objects from one type to another
Object t;
t as SomeType
if(t != null) {...}
  • Advantages
    • casts an object without an overhead of a try/catch block (returns null if cast fails)
  • Disadvantages
    • cannot be used on value types
cast - used to cast values from one type to another
  • Advantages
    • can be used to cast any types of values, whether reference or value.  Used in foreach loops for that reason (since collections could have either type)
    • ability to fail out of the class when casting an unexpected object is attempted 
  • Disadvantages
    • try/catch overhead
    • may force to insert business logic into the catch block

No comments:

Labels