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.
asis 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 throwsInvalidCastExceptionif the type cannot be cast.In other words, this code assigns
nullif Parent if not of type SPWeb:While the other version throws if Parent is not of the correct type:
The
asoperator 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 useasand then check for null.asonly 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(versusDirectCast).