October 2005 - Posts

castClass vs

Wanted to share a small note keeping in mind the "as" keyword .

public class Program
{
            public static void Main()
            {
                        object o = 100;
                        string s = o as string;
                        string t = (string) o;
            }
}

  IL_0000:  ldc.i4.s   100
  IL_0002:  box        [mscorlib]System.Int32
  IL_0007:  stloc.0
  IL_0008:  ldloc.0
  IL_0009:  isinst     [mscorlib]System.String 
  IL_000e:  stloc.1
  IL_000f:  ldloc.0
  IL_0010:  castclass  [mscorlib]System.String  
  IL_0015:  stloc.2
  IL_0016:  ret

 If you notice that "as"  is translated into isinst opcode and the advantage of using this is that it would return a null reference if the object of is not castable to a string.
On the other hand the castClass would throw an InvalidCast exception.

Start.com

I wished MS would get things out to more people and faster

http://start.com

with 0 Comments