General discussion


.NET: Boxing and unboxing

By MaryWeilage Editor ·
This week's .NET e-newsletter explains what the term boxing means and discusses how you can use it in your applications. The author also talks about reversing the boxing process, which is called unboxing.

What important details about boxing and unboxing do new developers need to understand? How often do you use boxing and unboxing in your shop? Can you think of any other .NET terms that might be confusing for newbies?

If you aren't subscribed to the free .NET e-newsletter, you can automatically subscribe to it by pasting the following URL into your browser: &subs_channel=bldr_front_door&list_id=e605&tag=fb

* Please delete any extra spaces that appear when you paste this URL into your browser.

This conversation is currently closed to new comments.

Thread display: Collapse - | Expand +

All Comments

Collapse -

'as' keyword also usable in some circumstances.

by btk120 In reply to .NET: Boxing and unboxing

It can be much faster in certain applications to use the 'as' keyword. 'As' does NOT work with value types like int, string, bool, etc.

Unlike the simple typecasting, 'as' returns a null in the destination variable if the cast failed instead of throwing an exception and requiring expensive try-catch blocks.*

The best use of this keyword I've seen in my limited use of .NET is strongly typed datasets.

Using the Select() function of a DataTable / DataSet returns an array of type System.Data.DataRow, even if you call it on a strongly typed DataSet (one that you make, among other ways, using the "Generate Data Set..." function of a Database Adapter in the UI.)

Using the 'as' keyword, you can simply check if the results are null and handle the case yourself.

* Caveat: I really don't know about the framework well enough to say that the 'as' keyword simply doesn't abstract the try/catch blocks from you. In such a case, the main advantage is not having to catch the exceptions yourself, and simply deal with the fact that it didn't happen.


Related Discussions

Related Forums