I’m wondering is there a way to overwrite Hashtable (or Dictionary) class so it would automatically do boxing/unboxing operations on objects. In other words:
myHashtable["value1"] = "this_is_string";
myHashtable["value2"] = 123;
string a = myHashtable["value1"];
int b = myHashtable["value2"];
// errors as expected, since i need to cast it to specific type from object
And apparently C# doesn’t allow overwriting public T this[object key] operator with different types, since I tried to do something like this:
public int this[object key] { get { return (base[key] as int); } set {} } // etc
public string this[object key] { get { return (base[key] as string); } set {} } // etc
// error
Any ideas or tips what is the simplest way (if any) to avoid casting while using associative arrays in C# (there’s no need to strictly use Hashtable)? And if there’s no way to do it, I would appreciate if someone more knowledgeable than me, explain why it is so and what are the fundamentals behind it.
Thank you.
Edit:
The reason I need it, is that I’m creating a custom Settings class. Settings might have different types of values, such as let’s say “HowManyItemsToDisplay” would have some integer value, while “NameOfSomeControl” would be a string. Therefore it would be nice to avoid any casting when writing something like:
myControl.Text = MySettings["SomeTextValue"];
or
while (MySettings["SomeIntValue"] > 0) { .. }
Assuming you have a good reason for doing this you could write an extension method to give you a reasonable way simulate that:
If you know the key is always a string you can make that the parameter type for the key and even use the generic dictionary or other structure with a strongly typed key.
And to be perfectly clear the casting and boxing are still there, just hidden from view.
Additional response to edit:
If you are able to use C# 4 I think you can pretty much get want you want syntactically with
Dictionary<object,dynamic>. Of course, if you are able to do that then you might just want to make the settings object dynamic and use the syntaxmySettings.Value1instead.