Reputation: 2818
I've seen this in a question: :
edit: type's are known before adding to dictionary
You could use Dictionary<string, object>, then you'd need to cast the results:
int no = 1;
string str = "world";
Dictionary dict = new Dictionary<string,object>();
dict.add( "intObj" , no );
dict.add( "intObj" , str );
int a = (int) Storage.Get("age"); //everthing was perfect till i see cast .
string b = (string) Storage.Get("name");
double c = (double) Storage.Get("bmi");
question: how can i modify square-Brackets [] to cast type before returnig value so it will look like this;
int a = dict["intObject"] ; //we got rid of casting forever
string b = dict["stringObject"] ;
thank you.
Upvotes: 0
Views: 670
Reputation: 149538
You can't directly modify the indexer. What you can do is create an extension method that does this (partially) for you:
public static class DictionaryExtensions
{
public static T Get<T>(this Dictionary<string, object> dictionary, string key)
{
object value = null;
return dictionary.TryGetValue(key, out value) ? (T)value : default(T);
}
}
Note this has a few shortenings:
If someone inserts a key with a null
, you'll get a cast exception at runtime if the value is a value type.
If the value doesn't exist for value types, you'll get the default for each primitive. Note this way you can't really indicate if the key was or was not present in the dictionary.
Upvotes: 2
Reputation: 1500525
(Answered before the .NET 2.0 requirement was mentioned - it may still be useful for others.)
You can use a Dictionary<string, dynamic>
instead - at which point the compile-time type of the expression dict["stringObject"]
will be dynamic
. The assignment to a variable of type string
will then perform the conversion at execution time.
You can't change how Dictionary<string, object>
behaves though. You would have to change the type argument... and no, you can't do this with .NET 2.0.
Upvotes: 1