Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an object from a dictionary of objects

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.

like image 787
cosmicsafari Avatar asked Dec 16 '22 17:12

cosmicsafari


1 Answers

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;
}
like image 93
JohnD Avatar answered Dec 30 '22 09:12

JohnD