Mohamed Saleh
Mohamed Saleh

Reputation: 27

{Equaling objects} "where is my object reference on ?" c#

I have one class named 'human' and 2 objects ( obj1 , obj2 ). and I have written below code

class human
{
    public static int x;
    public readonly int id;

    public human()
    {
        x++;
        id = x;
    }

    public void show()
    {
        Console.WriteLine("id = " + id);
    }
}


class Program
{
    static void Main(string[] args)
    {
        human obj1 = new human();
        human obj2 = new human();

        obj2 = obj1;
        Console.ReadKey();
    }
}

I know when I write that code ->> human obj2 = obj1;

obj2 reference on obj1 in heap

but in my code with this ->> human obj2 = new human();

and do that ->> obj2 = obj1;

is obj2 will update values in his object with obj1's values ??

or obj2 will reference on obj1

Thanks :)

Upvotes: 1

Views: 86

Answers (2)

Owen Pauling
Owen Pauling

Reputation: 11841

C# has value types and reference types. A value type directly stores the data, whereas a reference type contains a reference to the data. A class is a reference type.

Where you have:

human obj1 = new human();
human obj2 = new human();

you are creating two new variables containing references to different new instances of human.

When you do:

obj2 = obj1;

You are saying "take the reference that obj1 contains and assign it to obj2". This means obj1 and obj2 are now both referencing the same instance that obj1 initially referenced.

If you had, for example, some public property called Name, and you set:

obj1.Name = "Bob"

and then you accessed obj2.Name, you will find that you get the value "Bob", because both obj1 and obj2 are referencing the same instance.

In your example, you will notice that obj1 and obj2 both have the same Id.

Upvotes: 1

David Pilkington
David Pilkington

Reputation: 13620

As it is a class both obj1 and obj2 will reference the same object in memory (as they are reference types). A human object with an id of 1

Upvotes: 2

Related Questions