Code Sample for Hashtable Derivative for Type conversion

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello,

I am using Hashtable class in my application to store key/value pairs. It
works great except the types returned are all objects. As a result, there are
type-casts everywhere making the code very hard to read. I believe it should
be relatively easy to derive a class from Hashtable that returns appropriate
types for my application. I started writing it like this

public class PeerTable : Hashtable {
public new PeerTable Clone() {
return (PeerTable)base.Clone();
}
}

But I don't know
1. How to make it return "MyValueType" type when I use something like
myPeerTable[key].
2. How to set dictionaryentry.Key to "MyKeyType" and dictionaryentry.Value
to "MyValueType".

I appreciate your help.

Regards,
Vinay Agarwal
 
This was what generics are great at. 2.0 has generic Dictionary collection
for strong typing to your value. If you can only use 1.1, then I think the
only way to get that behavior is by wrapping the hashtable yourself and
implement the required methods and enumerator(s).
 
In .NET 1.1 and before, you would derive from the DictionaryBase class.
It provides most of the functionality you need, you just need to provide the
type-safe methods.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

William Stacey said:
This was what generics are great at. 2.0 has generic Dictionary
collection for strong typing to your value. If you can only use 1.1, then
I think the only way to get that behavior is by wrapping the hashtable
yourself and implement the required methods and enumerator(s).

--
William Stacey [MVP]

Vinay Agarwal said:
Hello,

I am using Hashtable class in my application to store key/value pairs. It
works great except the types returned are all objects. As a result, there
are
type-casts everywhere making the code very hard to read. I believe it
should
be relatively easy to derive a class from Hashtable that returns
appropriate
types for my application. I started writing it like this

public class PeerTable : Hashtable {
public new PeerTable Clone() {
return (PeerTable)base.Clone();
}
}

But I don't know
1. How to make it return "MyValueType" type when I use something like
myPeerTable[key].
2. How to set dictionaryentry.Key to "MyKeyType" and
dictionaryentry.Value
to "MyValueType".

I appreciate your help.

Regards,
Vinay Agarwal
 
Wow! I didn't know of this feature in 2.0. Since I am using 2.0, I will
simply switch to Dictionary instead of Hashtable.

I should hang out here more often to get ideas like this. :-) Thanks a lot.

Regards,
Vinay
 
Back
Top