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.
(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.
See more on this question at Stackoverflow