Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting with 'As' rather than (<T>)?

I've been reading up on SharePoint 2010 for work and I've noticed that many code examples I run into from books to instructional videos are cast SharePoint objects in a way I never knew existed in C# (and thought was VB exclusive):

SPWeb web = properties.Feature.Parent as SPWeb;

I'm so used to casting (outside of VB) this way (SPWeb)properties.Feature.Parent and was just curious if there was any particular reason most pieces on SharePoint I've encountered use the VB-esque casting notation.

like image 725
EHorodyski Avatar asked Jan 27 '26 12:01

EHorodyski


2 Answers

as is called the safe cast operator in C#. There is a semantic difference between that and a normal cast. A safe cast will not throw an exception if the type cannot be cast; it will return null. A normal cast throws InvalidCastException if the type cannot be cast.

In other words, this code assigns null if Parent if not of type SPWeb:

SPWeb web = properties.Feature.Parent as SPWeb;

While the other version throws if Parent is not of the correct type:

SPWeb web = (SPWeb)properties.Feature.Parent;

The as operator can be quite useful if you don't know for sure that an object can be cast to the desired type - in this case it is common to use as and then check for null. as only works on reference types, since value types cannot be null.

This is also explained in this longer article on MSDN.

By the way, the equivalent operator in VB is TryCast (versus DirectCast).

like image 191
driis Avatar answered Jan 29 '26 02:01

driis


obj as T

is syntax sugar for

obj is T ? (T)obj : null

Thus, it is a "safe" cast. However, it takes longer, in theory. Thus, you should use normal casting unless you specifically want null if an object is not of the expected type. More often, you are better off handling it manually:

if (!(obj is T))
{
    // Handle the case where obj is of an unexpected type.
}

T tobj = (T)obj;
like image 35
Zenexer Avatar answered Jan 29 '26 00:01

Zenexer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!