EHorodyski
EHorodyski

Reputation: 794

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.

Upvotes: 3

Views: 202

Answers (5)

Zenexer
Zenexer

Reputation: 19613

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;

Upvotes: 2

driis
driis

Reputation: 164281

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).

Upvotes: 6

If the cast fails the variable assigned to becomes null opposed to throwing an exception 'InvalidCastException '

Upvotes: 1

Chriseyre2000
Chriseyre2000

Reputation: 2053

"as" is safer than (cast) as it will either return a value as the given type or null. You will find that the following line will (or should) test for null.

Upvotes: 1

cory-fowler
cory-fowler

Reputation: 4088

Using the as keyword will set the variable web to null if the Parent is not of type SPWeb.

As where an explicit cast will throw an exception if the Parent is not of type SPWeb.

Upvotes: 1

Related Questions