Roy Osherove

View Original

A better Safe Cast using Generics

Update: the code has changed a bit in the C# version to reflect *exactly* the same behavior as "as". See the comments.
 
Here's a nice way to make something like the "as" word in C# apply to both value types and reference types. It takes advantage of Generics in .NET 2.0 and the "default" word in C#, which returns the default value for a given type. The equivalent to that word in VB.NET as far as I've found is "Nothing". 
 
With this function you can cast to any generic type you'd like, and if the value does not cast to it, you don't get an exception, but the default value for that type of object.
Important note: for value type, this will cause a boxing operation to occur and a little perf hit because of two type checks.
 
 
8:         private T safeCastTo<T>(object obj)
9:         {
10:             if (obj == null)
11:             {
                  //same behavior as "as"
12:                 return null;
                 //or you could return the default value if you need to
12:                 //return default(T);
13:             }
14:             if (!(obj is T))
15:             {
                  //same behavior as "as"
6:                 return null;
                 //or you could return the default value if you need to
12:                 //return default(T);

17:             }
18:             return (T )obj ;
19:         }
Or in VB.NET:

9:
    Function SafeCast(Of T)(ByVal value As Object) As T
10:         If value Is Nothing Then Return Nothing
11:         If TypeOf (value) Is T Then Return value
12:         Return Nothing
13:     End Function
have fun!