Daniel Little Coding Blog
Daniel Little Coding Blog

A blog about .net development and the web.

Daniel Little
Author

Daniel Little (lavinski) is a Brisbane based software developer.

Share


Our Newsletter


Like this blog? Get each new post as soon it's posted.

Tags


Twitter


C# and casting

Daniel LittleDaniel Little

I see alot of people using the as keywork where they really just want to do a cast. Most of the time a cast will be what you want because it's faster and will fail early when somthing goes wrong.

When should you cast?
You should cast when you already know what type the object is. A cast also will *not * fail your value is null.

var value = (Apple)appleDictionary[key];

When should you use as?
When you don't know the type of object.

bool makeA = true;
BaseClass baseClass = null;
baseClass = makeA ? new SuperClassA() : new SuperClassB();

SuperClassB val = baseClass as SuperClassB;
if (val != null) { //...

You will almost always be compairing the value to null after using as.

It's important to know as does not replace cast in any way, always pick the one you need for your situation.

Daniel Little
Author

Daniel Little

Daniel Little (lavinski) is a Brisbane based software developer.

Comments