|
-
Sep 9th, 2008, 03:04 AM
#1
Thread Starter
Hyperactive Member
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
» Twitter: @rudi_visser : Website: www.rudiv.se «
If Apple fixes security flaws, they are heralded as proactive. If Microsoft fixes a security flaw, they finally got around to fixing their buggy OS.
-
Sep 9th, 2008, 05:20 AM
#2
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();
-
Sep 9th, 2008, 08:01 AM
#3
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"];
-
Sep 17th, 2008, 01:48 PM
#4
Addicted Member
Re: I'm intrigued (object->int)
 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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|