---
title: "A better Safe Cast using Generics"
url: "https://osherove.com/blog/2005/11/9/a-better-safe-cast-using-generics.md"
canonical: "https://osherove.com/blog/2005/11/9/a-better-safe-cast-using-generics.html"
published: "2005-11-09T10:38:00"
updated: "2005-11-09T10:38:00"
tags: [".Net 2.0"]
author: "Roy Osherove"
description: "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…"
usage: "Licensed under CC BY 4.0 — reuse, quote and adapt with attribution (Roy Osherove, link to the original page)."
license: "https://creativecommons.org/licenses/by/4.0/"
---

# A better Safe Cast using Generics

By Roy Osherove November 9, 2005 In [.Net 2.0](https://osherove.com/blog/category/net-2-0)

**Historical article** · Originally published November 9, 2005; technical details may be outdated.

**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](http://www.c-sharpcorner.com/Code/2003/July/BoxNUnboxSSF.asp) 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!

## More in .Net 2.0

[All posts in .Net 2.0](https://osherove.com/blog/category/net-2-0)

- Nov 9, 2005

    ### [I'll be speaking at IVCUG this month: New stuff in .NET and C# 2.0 + Deep LINQ Preview](https://osherove.com/blog/2005/11/9/ill-be-speaking-at-ivcug-this-month-new-stuff-in-net-and-c-2.html)

- Nov 9, 2005

    ### [A better BackgroundWorker : CancelImmediately and other goodies](https://osherove.com/blog/2005/11/9/a-better-backgroundworker-cancelimmediately-and-other-goodie.html)

- Nov 4, 2005

    ### [My first real frustration with VS 2005 RTM](https://osherove.com/blog/2005/11/4/my-first-real-frustration-with-vs-2005-rtm.html)

- Oct 30, 2005

    ### [Amazoner 1.0.1 - Larger Images for Books and a dedicated website](https://osherove.com/blog/2005/10/30/amazoner-101-larger-images-for-books-and-a-dedicated-website.html)


---

## About the author

**Roy Osherove**: Senior Solutions Architect at AWS working on AI for production and AI-driven development; author of The Art of Unit Testing and Elastic Leadership, with about 20 years of consulting and training on unit testing, TDD, team leadership and continuous delivery.

### Sites

- [RobotPaper](https://robotpaper.ai/): This blog: AI patterns and anti-patterns, AI and coding agents, and engineering leadership.
- [osherove.com](https://osherove.com): Roy's personal site. Author of The Art of Unit Testing and Elastic Leadership; consulting and training on unit testing, TDD, team leadership and continuous delivery, plus about 20 years of blog posts.
- [The Art of Unit Testing](https://www.artofunittesting.com): The Art of Unit Testing, 3rd Edition (Manning): readable, maintainable, trustworthy unit tests, plus TDD workshops in C#, JavaScript, Java and Kotlin.
- [5whys.com](https://www.5whys.com): Roy's writing on software team leadership: self-organizing teams, surviving chaos, learning mode and the Elastic Leadership model.
- [Pipeline Driven](https://pipelinedriven.org): Continuous delivery and DevOps practices: build patterns, pipeline-friendly testing, DevOps metrics and enterprise DevOps.
- [Elastic Leadership](https://www.elasticleadership.com): Elastic Leadership, Roy's framework for software team leaders (survival, learning and self-organizing modes).

### Social

- X: https://x.com/royosherove
- LinkedIn: https://www.linkedin.com/in/osherove/

### Contact

- Contact form: https://forms.gle/jQSx5KoXvrVA1JCK7

### License

Licensed under CC BY 4.0 — reuse, quote and adapt with attribution (Roy Osherove, link to the original page). License: https://creativecommons.org/licenses/by/4.0/
