2

Possible Duplicate:
Casting vs using the ‘as’ keyword in the CLR

I know there are a lot of questions about casts but I don't know the specific names of these two casts so I'm not sure where to look. What are the differences between the two casts below?

TreeNode treeNode = (TreeNode)sender; // first cast
TreeNode treeNode = (sender as TreeNode); //second cast
Community
  • 1
  • 1
phadaphunk
  • 12,785
  • 15
  • 73
  • 107
  • 1
    The first is a "cast", the second is just the "as" operator (it is not literally a cast, it just contains a cast internally). Since you mentioned not knowing the names. – Servy Dec 10 '12 at 17:08
  • 1
    You can read more here: [Safely Cast by Using as and is Operators](http://msdn.microsoft.com/en-us/library/cc488006.aspx) – Zbigniew Dec 10 '12 at 17:09
  • Thanks now I know. I just didn't know the difference between a cast and the as operator that's why I had difficulty searching for the difference between these two – phadaphunk Dec 10 '12 at 17:10
  • -1 and no comments explaining what's wrong about my question. Love it – phadaphunk Dec 10 '12 at 17:11
  • 1
    I suspect the vote down is because of a question that can be answered by a quick google search of your question title – Ben Robinson Dec 10 '12 at 17:13

2 Answers2

13

The first type of cast is called an "explicit cast" and the second cast is actually a conversion using the as operator, which is slightly different than a cast.

The explicit cast (type)objectInstance will throw an InvalidCastException if the object is not of the specified type.

// throws an exception if myObject is not of type MyTypeObject.
MyTypedObject mto = (MyTypedObject)myObject;

The as operator will not throw an exception if the object is not of the specified type. It will simply return null. If the object is of the specified type then the as operator will return a reference to the converted type. The typical pattern for using the as operator is:

// no exception thrown if myObject is not MyTypedObject
MyTypedObject mto = myObject as MyTypedObject; 
if (mto != null)
{
    // myObject was of type MyTypedObject, mto is a reference to the converted myObject
}
else
{
    // myObject was of not type MyTypedObject, mto is null
}

Take a look at the following MSDN references for more details about explicit casting and type conversion:

Ian R. O'Brien
  • 6,682
  • 9
  • 45
  • 73
7

If sender is not a TreeNode than the first one throws exception and second one returns null.

Servy
  • 202,030
  • 26
  • 332
  • 449
L.B
  • 114,136
  • 19
  • 178
  • 224