views:

149

answers:

4

I've recently started working with JSON and the ExtJs framework and I've come across the following code in an example.

we retrieve the information from the frontend using this:

object updatedConfig = JavaScriptConvert.DeserializeObject(Request["dataForm"]);

Then in the example they do the following:

JavaScriptObject jsObj = updatedConfig as JavaScriptObject;

I've never seen the "as" keyword used like that before. Is this just another form of explicitly boxing the updatedConfig variable as a JavaScriptObject or is there something I'm not understanding about this?

Thanks

+2  A: 

The as keyword is a safer way to cast objects in C#.

SomeType a = obj as SomeType;

Means that if obj is of type SomeType, obj will be cast into that type. If obj is null or is not of type SomeType, a will be null.

siz
It's also faster to use 'as' and check for null than to check the type with 'is' and then do an hard cast. The type will be checked twice in the latter case.
Dave Van den Eynde
+2  A: 

This is 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.

There are actually two separate IL instructions to handle the difference between "as" casting and normal static casting. The following C# code contains both types of casting:

using System;

class Program
{
    static void Main()
    {
     Object o = null;

     String s0 = (String)o;
     String s1 = o as String;
    }
}

The first cast uses the castclass IL instruction and the second cast uses the isinst instruction.

Please see http://stackoverflow.com/questions/496096/casting-vs-using-the-as-keyword-in-the-clr for a more detailed explanation.

Andrew Hare
A: 

Another advantage of the as keyword is that it will throw a compile time exception if the type can not be cast where as (cast) doesn't break until run-time.

Sruly
A: 

Also, it's important to remember that "as" operates in the reference not in the object itself. That's why it can return null instead of throwing an exception, because the object will remain intact. And that's why you can only do it on reference types.

Normally it does not matter that much, but if you implement a casting function (like here in MSDN) it will not be invoked by using as operator.

So, the as operator is useful to "move up and down the inheritance hiearchy": If you have a class Person, you can do: Person p = new Person(); ojbect o = p as object; p = o as Person; But in all cases the object in memory won't be modified in any way, just the reference to it.

Hope that helps

Rafa G. Argente