C# dictionary idictionary access different class

32 Views Asked by At

If I want to register a user in class “add user” and then list all registered users in another class “list users” how should code be?

I have Person class

class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public Person(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
}

Then I Have window for Adding/registry

class AddView
{

    Dictionary<string, Person> _persons = new Dictionary<string, Person>();

    public void Display()
    {

        Console.WriteLine("Firstname");
        var firstname = Console.ReadLine();

        Console.WriteLine("Lastname");
        var lastname = Console.ReadLine();

        var per = new Person(firstname,lastname);

        _persons.Add(per.FirstName, per);

        Console.WriteLine("added");
        Console.ReadKey();

        var main = new MainView();
        main.Display();
    }
}

Then I want to display all I added in different window/ class

class ListView
{

    public void Display()
    {

Here comes this problem I cant get access to data that I registered In Add Person class

        foreach (var p in _persons)
        {
            Console.WriteLine(p.Value.FirstName);

        }

    }
}
0

There are 0 best solutions below