Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linkable variable type

Tags:

variables

c#

ref

Which variable types can be linked? I have tried to use object but it didn't do what I want.

object a;
object b;
b = 5;
a = b;
b = 2;
label1.Text = Convert.ToString(a);

It writes 5 but I want it to be 2.

like image 577
halil12 Avatar asked Jun 09 '26 02:06

halil12


1 Answers

This is a simple misunderstanding of references and how they work, and what variables are.

object a; // a is a storage location
          // it holds references to instances of object

object b; // b is a storage location
          //it holds references to instances of object

b = 5; // "boxes" 5 into an instance of object
       // and assigns reference to that object to b

a = b; // assigns reference in storage location b to storage location a

b = 2; // "boxes" 2 into an instance of object
       // and assign reference to that object to b

Think of it like this. a and b are pieces of paper that hold addresses to homes on them. When you say b = 5, think of it as writing down the address to a home 5 on the piece of paper b. When you say a = b, think of it as copying the address that is written on b to a. When you say b = 2, think of it as erasing the address that is written on b and replacing it with the address to home 2. This action does not change the value that is written on the piece of paper a. That's what is happening here.

Now, let's look at a very simple way to make what you're trying to do work.

class MyValue {
    public int Value { get; set; }
}

MyValue b = new MyValue { Value = 5 }; 
MyValue a = b;
b.Value = 2;

Now, if you say

Console.WriteLine(a.Value);

what will happen? Let's reason carefully. Again, back to the analogy of a and b as pieces of paper with addresses written on them. We have said MyValue b = new MyValue { Value = 5 }. Think of this as writing down on the piece of paper b the address to a home with a sign saying 5 above the front door. Think of a = b as copying the address that is written on b to a. And then, think of b.Value = 2 as changing the value on the sign above the front door, in this case, changing the 5 to 2. Now, if someone asks, what is the value above the door on the home that has the address that is written on the piece of paper a? Well, the address on a is the same as the address on b. We just changed the value on the sign above the front door from 5 to 2. So, we expect to see 2.

Try it, try it, and you will see the value 2 printed to the console.

Think about this over and over and over until you feel it deep in your bones. Until you grasp this fundamental concept, you will find reasoning about programming to be quite challenging.

like image 193
jason Avatar answered Jun 10 '26 15:06

jason