I'm intrigued (object->int)
Hi everyone
Not a question on how to do something, just why the following isn't possible (As an example):
Code:
Hashtable ht = new Hashtable();
ht.Add("test", 5);
int blah = (int)ht["test"];
I think it's strange but I haven't exactly read the whole C# spec to find out, just wondering if anyone knows :)
Re: I'm intrigued (object->int)
What's not working? Is it throwing any error, Compile time error or run time error?
I just gave it a try and it worked perfectly.
This is the code I used:
Code:
System.Collections.Hashtable ht = new System.Collections.Hashtable();
ht.Add("test", 5);
int num = (int)ht["test"];
Console.Write("Entered value: {0}", num);
Console.ReadLine();
Re: I'm intrigued (object->int)
Not an answer to the question specifically but, from .NET 2.0 onwards, don't use Hashtables, ArrayLists or any of those untyped collections. Use Dictionaries, Lists and other generic collections. No casting required.
Code:
Dictionary<string, int> d = new Dictionary<string, int>();
d.Add("test", 5);
int i = d["test"];
Re: I'm intrigued (object->int)
Quote:
Originally Posted by jmcilhinney
Not an answer to the question specifically but, from .NET 2.0 onwards, don't use Hashtables, ArrayLists or any of those untyped collections. Use Dictionaries, Lists and other generic collections. No casting required.
Code:
Dictionary<string, int> d = new Dictionary<string, int>();
d.Add("test", 5);
int i = d["test"];
J,
I then have a question about how to best handle a situation I'm dealing with now. My team is working on an app that has evolved from 1.1. We're currently targeting the 3.5 framework, so we have all those goodies available to us. If I'm going to suggest we refactor the code, though, I'd like to have a solid suggestion.
Currently, we store a hashtable in session state to manage a number of items used between pages in an ASP.NET app. There are severl different object types stored in the hashtable (strings, ints, custom objects, ect...). This strikes me as inefficient. After all, the hash table needs to be cast back into a HT from an object when it's pulled from session state and then each object in-turn needs to be cast into its type when being pulled from the hashtable. Seems like a lot of wated CPU cycles to me. Any thoughts, links to best practices, etc. Optimally a type safe way to store and retrieve the objects from session state.