Casting Call

Something short and to the point today.  I was talking to my office roommate this morning about old school coding habits vs newer syntax styles and the subject of “casting” came up.

You see, I’ve done casting like this for years and years…

string example = null;
example = (string)e.Value;

and when I started doing more coding with telerik controls, I see all their samples do casting like this

string example = null;
example = e.Value as string;

I didn’t think anything of it at first, just thinking the “as” way was just a newer way to do it that was a bit more readible…however my co-worker let me know that they actually do different things.

In my first example if you try to cast something that’s not a string into the “example” variable you will get an InvalidCastException thrown.

In my second example if you try to cast something that’s not a string into the “example” variable…”example” will just be equal to null.  That’s useful when you’re not absolutely sure what kind of type you’re dealing with and saves you from having to put up try \ catch blocks everywhere.

Anyway…this was just a quick useful piece of info I happened across today and thought I’d leave a blog post about it.  Hope it helps…Enjoy!  🙂

Advertisements
Casting Call

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s