Yes, there is much cleaner approach. Actually, your solution is pretty dirty from the very beginning: you are using a non-generic hash table which inherently based on type casting. In other words,
compile-time element type is
System.Object
, so you need to do type casts if you store objects of other types (which are still objects but have different
run-time types).
All such collections (except specialized ones) have been rendered obsolete as early as of .NET v.2.0, when generics were introduced. The were not formally marked with
System.ObsoleteAttribute
just because there is nothing wrong with using it in legacy software units, for compatibility, but using them in newly developed software makes no sense, ever.
In your case, you should use the type
System.Collections.Generic.Dictionary<string, string>
:
http://msdn.microsoft.com/en-us/library/xfhwa508.aspx[
^].
See also:
http://msdn.microsoft.com/en-us/library/System.Collections.Generic.aspx[
^].
Non-generic non-specialized collections have gone, don't use them anymore.
[EDIT]
As I see you are still confused with the cast. You need to understand how strings are compared and how default comparison between reference-type objects is done. Normally, references are compared. But you can redefine comparison method
System.Object.Equals(System.Object)
, to compare object in some different way, let's say, semantically. If this is done, you have a choice between "==" comparison (which can be redefined separately) and comparison which always checks referential identity, using
System.Object.ReferenceEquals
. Please see:
http://msdn.microsoft.com/en-us/library/system.object.aspx[
^].
Compiler does not "know" that one operand is a string and compares references, which is not what you meant to do. For strings, it compares string contents.
System.String
is a reference class which closely mimic value semantic. It is much more complex then most people think. For understanding, please see:
http://msdn.microsoft.com/en-us/library/system.string.intern.aspx[
^],
http://msdn.microsoft.com/en-us/library/system.string.isinterned.aspx[
^],
http://en.wikipedia.org/wiki/String_intern_pool[
^].
You really need to understand reference and value types and working with references. These concepts are fundamental to .NET and CLI.
—SA