Dib
Dib

Reputation: 67

C# Using a Class as object in a Dictionary

I'm a newbie on C# and I have some issues with a code I'm trying to write.

I have to make a simple program that stores some info on students and later, let me get the info to print.

My idea was this: I created a class, named "Aluno" and implemented a series of methods to set and get the info I needed, and then I passed this class as parameter to a Dictionary Something like this:

 class Aluno
    {
        private int matricula;
        private string nomeCompleto;

        public int getMatricula() { return matricula; }
        public string getNomeCompleto() { return nomeCompleto;

        public void setMatricula(int m)
        {
            matricula = m;
        }
        public void setNomeCompleto(string nome)
        {
            nomeCompleto = nome;
        } 

Then i used it in a dictionaty

        Dictionary<int,object> principal =  new Dictionary<int,object>();
        Aluno a = new Aluno();

        Console.WriteLine("Por favor informe a matricula:");
        a.setMatricula(int.Parse(Console.ReadLine()));
        Console.WriteLine("Por favor informe o nome completo do aluno:");
        a.setNomeCompleto(Console.ReadLine().ToUpper());

        principal.Add(a.getMatricula(), a);

After this, I implemented a class to print the info stored on dictionary:

class ImprimeListagem
    {
        public static void listagemSimples(Dictionary<int,object> origem)
        {
            int contador = 0;

            foreach (KeyValuePair<int, object> chave in origem)
            {
                Console.WriteLine(chave.Key+"|"+chave.Value);

                Console.ReadKey();
            }

        }

when I use Visual studio to "look" inside chave.value, all the info stored is there, but I cant access it. Can someone help me? I'll print the entire code.

class Program
{
    static void Main(string[] args)
    {
        const int QTDE_ALUNO_PRINCIPAL = 1;
        const int QTDE_ALUNO_RESERVA = 1;            
        int contadorAlunosPrincial = 0;
        int contadorAlunoReserva = 0;


        Dictionary<int,object> principal =  new Dictionary<int,object>();
        Queue<object> espera = new Queue<object>();

        Aluno a = new Aluno();

        int opcao = 0;



        do
        {
            ImprimeMenu.imprimirMenuPrincipal();
            opcao = int.Parse(Console.ReadLine());

            switch (opcao)
            {
                case 1:
                    if (contadorAlunosPrincial < QTDE_ALUNO_PRINCIPAL)
                    {
                        Console.Clear();
                        Console.WriteLine("Por favor informe a matricula:");
                        a.setMatricula(int.Parse(Console.ReadLine()));
                        Console.WriteLine("Por favor informe o nome completo do aluno:");
                        a.setNomeCompleto(Console.ReadLine().ToUpper());
                        Console.WriteLine("Por favor informe o nome da mãe:");
                        a.setNomeDaMae(Console.ReadLine().ToUpper());
                        Console.WriteLine("Por favor informe o nome do pai:");
                        a.setNomeDoPai(Console.ReadLine().ToUpper());
                        Console.WriteLine("Por favor informe o país");
                        a.setEnderecoPais(Console.ReadLine().ToUpper());
                        Console.WriteLine("Por favor informe o estado:");
                        a.setEnderecoEstado(Console.ReadLine().ToUpper());
                        Console.WriteLine("Por favor informe a rua e o numero");
                        a.setEnderecoRuaNumero(Console.ReadLine().ToUpper());
                        Console.WriteLine("Por favor informe o cep");
                        a.setEnderecoCep(Console.ReadLine().ToUpper());
                        Console.WriteLine("Por favor informe o telefone para contato:");
                        a.setTelefoneContato(Console.ReadLine().ToUpper());

                        principal.Add(a.getMatricula(), a);

                        contadorAlunosPrincial++;

                    }
                    else
                        if (contadorAlunoReserva < QTDE_ALUNO_RESERVA)
                        {
                            Console.Clear();
                            Console.WriteLine("Por favor informe a matricula:");
                            a.setMatricula(int.Parse(Console.ReadLine()));
                            Console.WriteLine("Por favor informe o nome completo do aluno:");
                            a.setNomeCompleto(Console.ReadLine().ToUpper());
                            Console.WriteLine("Por favor informe o nome da mãe:");
                            a.setNomeDaMae(Console.ReadLine().ToUpper());
                            Console.WriteLine("Por favor informe o nome do pai:");
                            a.setNomeDoPai(Console.ReadLine().ToUpper());
                            Console.WriteLine("Por favor informe o país");
                            a.setEnderecoPais(Console.ReadLine().ToUpper());
                            Console.WriteLine("Por favor informe o estado:");
                            a.setEnderecoEstado(Console.ReadLine().ToUpper());
                            Console.WriteLine("Por favor informe a cidade:");
                            a.setEnderecoCidade(Console.ReadLine().ToUpper());
                            Console.WriteLine("Por favor informe o bairro:");
                            a.setEnderecoBairro(Console.ReadLine().ToUpper());
                            Console.WriteLine("Por favor informe a rua e o numero");
                            a.setEnderecoRuaNumero(Console.ReadLine().ToUpper());
                            Console.WriteLine("Por favor informe o cep");
                            a.setEnderecoCep(Console.ReadLine().ToUpper());
                            Console.WriteLine("Por favor informe o telefone para contato:");
                            a.setTelefoneContato(Console.ReadLine().ToUpper());

                            espera.Enqueue(a);

                            contadorAlunoReserva++;
                        }
                        else
                            Console.WriteLine("Não há mais vagas para cadastro de Alunos!\nTente novamente mais tarde.");

                    break;

                case 2:
                    ImprimeMenu.imprimirMenuSecundário();
                    opcao = int.Parse(Console.ReadLine());
                    switch (opcao)
                    {
                        case 1:
                            ImprimeListagem.listagemSimples(principal);
                            break;
                        case 2:
                            break;
                    }
                    break;

            }
        } while (opcao != 7);

    }

    class ImprimeMenu
    {
        public static void imprimirMenuPrincipal()
        {
            Console.Clear();
            Console.WriteLine("Programa de cadastro de alunos! Escolha a opção desejada.\n\n" +
                "1 – Cadastrar aluno\n" +
                "2 – Imprimir lista de alunos\n" +
                "3 – Imprimir lista de espera\n" +
                "4 – Pesquisar aluno\n" +
                "5 – Desistência\n" +
                "6 – Sorteio\n" +
                "7 – Sair");
        }
        public static void imprimirMenuSecundário()
        {
            Console.Clear();
            Console.WriteLine("2 – Imprimir lista de alunos\n\n" +
                "\t1 – Listagem simples\n" +
                "\t2 – Listagem completa");
        }
    }

    class Aluno
    {
        public Aluno()
        {
            matricula = 0;
            nomeCompleto = null;
            nomeDaMae = null;
            nomeDoPai = null;
            enderecoPais = null;
            enderecoEstado = null;
            enderecoCidade = null;
            enderecoBairro = null;
            enderecoRuaNumero = null;
            enderecoCep = null;
            telefoneContato = null; 
        }            

        private int matricula;
        private string nomeCompleto;
        private string nomeDaMae;
        private string nomeDoPai;
        private string enderecoPais;
        private string enderecoEstado;
        private string enderecoCidade;
        private string enderecoBairro;
        private string enderecoRuaNumero;
        private string enderecoCep;
        private string telefoneContato;

        public void setMatricula(int m)
        {
            matricula = m;
        }

        public void setNomeCompleto(string nome)
        {
            nomeCompleto = nome;
        }

        public void setNomeDaMae(string nomeMae)
        {
            nomeDaMae = nomeMae;
        }

        public void setNomeDoPai(string nomePai)
        {
            nomeDoPai = nomePai;
        }

        public void setEnderecoPais(string pais)
        {
            enderecoPais =  pais;
        }

        public void setEnderecoEstado(string estado)
        {
            enderecoEstado = estado;
        }

        public void setEnderecoCidade(string cidade)
        {
            enderecoCidade = cidade;
        }

        public void setEnderecoBairro(string bairro)
        {
            enderecoBairro = bairro;
        }

        public void setEnderecoRuaNumero(string ruaNumero)
        {
            enderecoRuaNumero = ruaNumero;
        }

        public void setEnderecoCep(string cep)
        {
            enderecoCep = cep;
        }

        public void setTelefoneContato(string telefone)
        {
            telefoneContato = telefone;
        }

        public int getMatricula() { return matricula; }
        public string getNomeCompleto() { return nomeCompleto; }
        public string getNomeDaMae() { return nomeDaMae; }
        public string getEnderecoPais() { return enderecoPais; }
        public string getEnderecoEstado() { return enderecoEstado; }
        public string getEnderecoCidade() { return enderecoCidade; }
        public string getEnderecoBairro() { return enderecoBairro; }
        public string getEnderecoRuaNumero() { return enderecoRuaNumero; }
        public string getEnderecoCep() { return enderecoCep; }
        public string getTelefoneContato() { return telefoneContato; }           

    }

    class ImprimeListagem
    {
        public static void listagemSimples(Dictionary<int,object> origem)
        {

            foreach (KeyValuePair<int, object> chave in origem)
            {
                Console.WriteLine(chave.Key+"|"+chave.Value);

                Console.ReadKey();
            }

        }            
    }

Thanks in advance and sorry about my poor english, it's not my native language. :D

Upvotes: 3

Views: 462

Answers (2)

TravellingGeek
TravellingGeek

Reputation: 1651

You need to explicitly cast the Object that you get from Dictionary to your class Aluno like this ((Aluno)chave.Value)

Upvotes: 2

Alexei Levenkov
Alexei Levenkov

Reputation: 100547

Looks like you want:

Dictionary<int,Aluno> principal =  new Dictionary<int,Aluno>();

In general it is extremely rare when one need to use object and parameter of generic type. In most cases you should use concrete type (or interface).

If you really find yourself with object value; instead of concrete type - you can cast it to type you expect "value" to be: MyType = (MyType)value;.

Upvotes: 5

Related Questions