Click here to Skip to main content
15,886,137 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have the problem, that I don't know how to get the properties of an object that is listed in a dictionary.

E.g.
C#
public class Person
{
   private string _name;

   public string Name
   {
      get { return _name; }
      set { _name = value; }
   }
}

In another class I created some objects from "Person" with the names Peter, Paul and Marie and saved them in a dictionary like this:

Dictionary<string,> persons = new Dictionary<string,>();
C#
persons.Add("Person1", new Person{ Name = Peter });
persons.Add("Person2", new Person{ Name = Paul });
persons.Add("Person3", new Person{ Name = marie });


Now I want to get the value of the property "Name" from the object which is paired with the key "Person1".

How to solve this problem??

EDIT:

It just made "click" in my head and I found the solution which will work for my situation:

C#
Person personName;

persons.TryGetVale("Person1", out personName);

string wantedName = personName.Name;


Sorry that I opened this question... I did not think that I get the solution just a few minutes later than I asked this question...
Posted
Updated 24-Nov-14 2:08am
v2

1 solution

The usual way to read from a dictionary would be
C#
string watsername = persons["Person3"].Name;
As you already hinting by your use of TryGetValue(), You should properly handle the possibility that Person3 may or may not exist in the dictionary.
 
Share this answer
 
Comments
ToShX 24-Nov-14 8:30am    
Thank you for your answer. It works :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900