A
A
Alexey Zus2017-04-14 21:41:15
.NET
Alexey Zus, 2017-04-14 21:41:15

Use of one variable by several objects. How does this happen?

Hi all!

using System;

namespace ConsoleApp1
{
   class AppObject
    {
        static int Main()
        {
            People humanoid_1 = new People("Name1");
            People humanoid_2 = new People("Name2");
            humanoid_1.peopleMetod();
            humanoid_2.peopleMetod();

            return 0;
        }
    }
    class People
    {
        string humanoid_name;

        public People(string name)
        {
            humanoid_name = name;
         }
        
        public void peopleMetod()
        {
            Console.WriteLine(humanoid_name);
        }

    }
}

When creating each instance, a parameterized constructor is called, in which all statements are executed, i.e. in this case, the variables declared in the class are initialized.
I don't understand how 2 different values ​​are written to one variable. I thought that it was being rewritten, but then I realized that it was absurd. When a method is called with a reference to one of the objects, the value of the variable of this object is displayed ... And how does the method process this variable?
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Tom Nolane, 2017-04-14
@lesha-proger

I don't understand how 2 different values ​​are written to one variable

People humanoid_1 = new People("Name1"); // humanoid_1 -> переменная раз
            People humanoid_2 = new People("Name2"); // humanoid_2  -> переменная дваз

tobish already two different variables of type People.
All value types derive from the System.ValueType type and place their value on the stack.
So you've created two reference type variables People. Reference types are stored on the heap. And when you create an object of a reference type , a reference to the address on the heap is placed on the stack. Main tobish: you have two heaps) People humanoid_1 = new People("Name1");

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question