2

Possible Duplicate:
C# “as” cast vs classic cast

I've inherited some code and I see this Grid event handler. I don't know if there's a difference between these two statements, I wouldn't think there is, but the fact that they are back to back in the code makes me wonder why do the same thing two ways (assuming they do the same thing). Could someone explain the difference, if any?

            GridDataItem ParentItem = e.Item as GridDataItem;

            GridDataItem NewRow = (GridDataItem)e.Item;
Community
  • 1
  • 1
Carlos Mendieta
  • 860
  • 16
  • 41

7 Answers7

6

"The as operator is like a cast operation. However, if the conversion is not possible, as returns null instead of raising an exception"

"Note that 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."

Read More

J Max
  • 2,371
  • 2
  • 25
  • 42
3

First one: ParentItem will be null if e.Item is not of the Type GridDataItem.

The second: It will throw an Exception, if e.Item is not of the type GridDataItem

citronas
  • 19,035
  • 27
  • 96
  • 164
2
//This will perform a safe conversion.  Null will be retuirned if e.Item is not
//a GridDataItem
GridDataItem ParentItem = e.Item as GridDataItem;

//This will throw an exception if e.Item is not a GridDataItem
GridDataItem NewRow = (GridDataItem)e.Item;

See FAQ: http://blogs.msdn.com/b/csharpfaq/archive/2004/03/12/what-s-the-difference-between-cast-syntax-and-using-the-code-as-code-operator.aspx

NinjaNye
  • 7,046
  • 1
  • 32
  • 46
2

These are two different ways to cast e.Item to a GridDataItem, depending on how you want the scenario where e.Item is not a GridDataItem to be handled.

In the first case, using as: you will always get a result, but if e.Item is not a GridDataItem that result will be null.

In the second case, using an explicit cast: if e.Item is not a GridDataItem, then your code will throw an InvalidCastException (which you can catch).

Bobson
  • 13,498
  • 5
  • 55
  • 80
1

The first line will ensure that ParentItem is null if typecasting is not possible. The second line will throw an exception

Dhawalk
  • 1,257
  • 13
  • 28
1

Using "as" instead of the explicit cast will not throw an exception if the conversion fails, but instead return null.

heisenberg
  • 9,665
  • 1
  • 30
  • 38
0

If e is a GridDataItem, no différences. If not : the "as" operator will return Null the "impossible catch" will throw an exception

So the difference is "just" how you handle false situations.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Stephane Halimi
  • 408
  • 3
  • 5