Search The Blog
About this site

@RoyOsherove

Subscribe!

This site aims to connect all the dots of my online activities - from tools, books blogs and twitter accounts, to upcoming conferences, engagements and user group talks.

from 5whys.com
Twitter: @RoyOsherove
My Book: The Art of Unit Testing
Latest Posts
« A better BackgroundWorker : CancelImmediately and other goodies | Main | The Browser Book - cool bunch of cheat sheets »
Wednesday
Nov092005

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!

PrintView Printer Friendly Version

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>