Rizwan Khan
Rizwan Khan

Reputation: 401

How to access Dictionary from other Class's function in C#?

I have create a Class named "EngDictionary". and Then i define a dictionary in a function e.g:

public void Dict()
    {
        Dictionary<string, string> d = new Dictionary<string, string>();
        d.Add("Classifieds", "Kleinanzeigen");
        //d.Add("windows", 5);   
    }

Now i want to access above defined dictionary from my main class for retrieving the keys and values of my Dictionary. Please Suggest me some code. I am using Visual C# 2008 Express Edition, Win Application

Upvotes: 0

Views: 16388

Answers (4)

aaron lilly
aaron lilly

Reputation: 274

I have a class

 public class Dict
    {
        public Dictionary<string, string> SomeDictionary { get; } = new Dictionary<string, string>()
        {
            { "Classifieds", "Kleinanzeigen" }
        };
    }

then in any other class

  Dict Dic = new Dict();
            
            foreach (var item in Dic.SomeDictionary)
            {
                Console.WriteLine(item.Key);
                Console.WriteLine(item.Value);
            }

Upvotes: -1

evilone
evilone

Reputation: 22740

Declare Dictionary as class property.

public class Dict {

   private Dictionary<string, string> dict;
   public SomeDictionary { get dict; set dict = value; }

   public Dict() {
      dict = new Dictionary<string, string>();
      dict.Add("Classifieds", "Kleinanzeigen");
   }
}

In other class:

Dict d = new Dict();
string test = d.SomeDictionary["Classifieds"];
Console.WriteLine(test);

Upvotes: 4

abhinav
abhinav

Reputation: 3217

return the dictionary from the method.

public Dictionary<string, string> Dict() {.... ; return d;}

In your main class.

EngDictionary dict = new EngDictionary();
Dictionary<string, string> dictionary = dict.Dict();

Upvotes: 1

Sandeep Pathak
Sandeep Pathak

Reputation: 10747

You can declare Dictionary<string, string> d as a member variable of your class , and initialize this object in the class constructor.You can have a getter method to get the dictionary in other classes.

public class EngDictionary
{
    Dictionary<string, string> dictionary;
    public void EngDictionary()
   {
        dictionary = new Dictionary<string, string>();
        dictionary.Add("Classifieds", "Kleinanzeigen");
        ....
    }

   public Dictionary<string, string> getDictionary()
   {
         return this.dictionary;
   }

 }

Upvotes: 0

Related Questions