I’m trying to pull an object from a dictionary of objects, and return said object however I’m having a bit of a problem with types. The class in question looks something like this, I’m wondering how I go about returning the actual object rather than the variable (which I assume is a string by default).
public Object GetObject(string foo){
if(someDict.ContainsKey(foo))
{
var pulledObject = someDict[foo];
}
return pulledObject;
}
I had thought boxing was needed, something like
object pulledObject = someDict[foo];
But that doesn’t seem to work, any advice that could point me in the right direction.
You don’t really say what isn’t working, but you are on the right track. Try something like this:
I suspect your problem was that you were getting a compile error with
pulledObjectwhich was in a child scope.Update: As Jon Skeet points out, it’s even better to use TryGetValue so you don’t perform the lookup twice (once when doing ContainsKey, and again when you use the indexer []). So, better solution is: