L
L
Ledington2021-09-20 10:56:38
C++ / C#
Ledington, 2021-09-20 10:56:38

How to make multiple variables on request?

I don't understand how to write something like this: var s = new Test("a", "b", "c");
It seems to be done through params, but how can I write it down so that I can access it?
Here is my class:

public class Test 
    {
        private List<string> _elements = new List<string>();

        public void AddElement(string x)
        {
            string AddElement = x;
            _elements.Add(AddElement);
            Console.WriteLine($"Элемент <{AddElement}> добавлен.");
            Console.WriteLine($"Стэк: {String.Join("; ", _elements)}");
            Console.WriteLine();
        }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2021-09-20
@Ledington

There are two ways:

Through constructor with params

public class Test 
    {
        public Test(params string[] elements) {
            foreach(var element in elements)
                AddElement(element);
        }   
        private List<string> _elements = new List<string>();

        public void AddElement(string x)
        {
            string AddElement = x;
            _elements.Add(AddElement);
            Console.WriteLine($"Элемент <{AddElement}> добавлен.");
            Console.WriteLine($"Стэк: {String.Join("; ", _elements)}");
            Console.WriteLine();
        }
}

var x = new Test("a", "b", "c");

Via Collection Initializer

public class Test 
    {
        private List<string> _elements = new List<string>();
        // Для Collection Initializer нужен публичный метод Add
        public void Add(string element) => AddElement(element); 
        public void AddElement(string x)
        {
            string AddElement = x;
            _elements.Add(AddElement);
            Console.WriteLine($"Элемент <{AddElement}> добавлен.");
            Console.WriteLine($"Стэк: {String.Join("; ", _elements)}");
            Console.WriteLine();
        }
}

var x = new Test { "a", "b", "c" };

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question