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:
public Object GetObject(string foo){
if (someDict.ContainsKey(foo))
return someDict[foo];
return null;
}
I suspect your problem was that you were getting a compile error with pulledObject
which 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:
public Object GetObject(string foo){
object pulledObject = null;
someDict.TryGetValue(foo, out pulledObject);
return pulledObject;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With