A
A
Artyom2018-11-14 18:29:27
C++ / C#
Artyom, 2018-11-14 18:29:27

How to access a property of an instance of a class that is in an array?

I have a loop that creates n instances of a class. This instance has 2 properties that are assigned from the keyboard. As a result, I get a list with objects. How can I get the values ​​of any properties and output/overwrite them in those objects?

int n = Convert.ToInt32(Console.ReadLine());
            ArrayList processes = new ArrayList();
            for (int i = 0; i < n; i++)
            {
                
                int a = Convert.ToInt32(Console.ReadLine());
                int b = Convert.ToInt32(Console.ReadLine());
              
                processes.Add(new Potok
                {
                    ProcComplete = a,
                    ProcArrive = b
                });
            }
            for(int i = 0; i < n; i++)
            {
                Console.WriteLine(processes[i]);
            }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Chernogorsky, 2018-11-15
@covaxi

Why not do this:

using System.Collections.Generic;
...
var processes = new List<Potok>()
...
Console.WriteLine(processes[i].PropName);

A
Artyom, 2018-11-14
@danyvasnafig

In, it turned out, initially I didn’t take processes[i] in separate brackets and didn’t specify the type, so it didn’t work.

for(int i = 0; i < n; i++)
            {             
                Console.WriteLine(((Potok)processes[i]).PropName);
            }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question