Wednesday, July 20, 2005

Casting Object types to their relevant types

This was something that I came across on codeguru. A guy had some issues while casting his object (base Object class' reference type).

Here's the question - "How can we convert objects to arraylists ?" (kind of a little specific to ArrayLists but could be any types in general that is derived from the base class "Object".)

Here's the answer : "Simple casting. How to do that? Its easy!"

Like suppose you store an arraylist into a session collection then what it returns is an object type. So, for it to be usable we need to get it casted to the original type it was.So you could simply do:

[CODE]
ArrayList myArrayList = (ArrayList) obj;

where obj is retrieved from Session by something like:

[CODE]
//put into session
Session["ArrayList"] = someArrayList;
//retrieve from session into an Object obj;
obj = Session["ArrayList"];
//and then back into our ArrayList type as mentioned above
ArrayList myArrayList = (ArrayList) obj;

You can also use the 'as' operator (safe-cast). (this was suggested by others):

[CODE]
//if obj is your ArrayList-object
ArrayList myList = obj as ArrayList;
if (null != myList){
//do something with your list
}

Oh..we can for sure argue about the better way whole night long. But it surely depends upon your style of doing things. You would get a null when the casting fails using the 'as' operator but sometimes that would be something that would sound like an exception rather than a null check (won't it?).

You would better check null if there are any items in your arraylist or has it been fully built up and handle the exception when you feel that there has something happened that made your object not hold something of an ArrayList reference type. Basically, if you get a null you wont be able to guess as to what is the reason? (or would you ??)

Had my arraylist stored in object Obj not properly initialized or is it some incompatible type related issue? So, you would agree that its usually better to keep different kind of exceptions/errors separetely handled as you might need that information. But anyways, it all depends on the logic you are trying to follow.Also, the 'as' operator works only for reference types.

You might wish to look at this article - http://www.aspheute.com/english/20001019.asp - to get a better feel about the is-operator and the as-operator. I would vote for using the direct casting as it would help you keep the invalid object error seperated away from the incompatible object exception. Cheers.

Monday, July 11, 2005

Learning C#

This blog would be a collection of some quality issues related to the C# Programming Language. A compilation of my activities on Codeguru. Hope this comes out to be of help to you people and of course me.

Cheers to my 3rd blog.
[ http://abnegator.blogspot.com ]