Monday 20 June 2011

As Operator in C#



The as operator is used to perform certain types of conversions between compatible reference types. "As" Operator is also known as a safe cast. What is does is it attempts to cast from one type to another and if the cast fails it returns null instead of throwing an InvalidCastException.


As-casting is equivalent to the following expression except that expression is evaluated only one time.

expression is type ? (type)expression : (type)null




Example


using System;

class Program

{

     static void Main()

     {

         Object o = null;

         // Prefix Casting

        String s0 = (String)o; //throw exception InvalidCastException
       

        //As Casting

       
        String s1 = o as String; // return null , instead of throwing an InvalidCastException


     }

}



Note



The as operator only performs reference conversions and boxing conversions. The as operator cannot perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.




There are actually two separate IL instructions to handle the difference between As-casting and Prefix-casting. The Prefix-casting cast uses the castclass IL instruction and the As-casting cast uses the isinst instruction.

Difference between As-casting and Prefix-casting :

Prefix-casting versus as-casting in C#

Who's Afraid of the big-bad cast operator?

1 comment:

  1. This is very nice post i had found. i will implement this in my coding. Thanks

    ReplyDelete