Click here to Skip to main content
15,885,079 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
We have such options like ref and out.
I wanna do like next:

int a = 5;
int b = a;
a = 10;
b should change to equal 10.

So, how?
Posted
Updated 17-Feb-15 22:31pm
v3

You can create a property:
C#
int _a;
int a
{
    get
    {
        return _a;
    }
    set
    {
        _a = value;
        _b = value;
    }
}

int _b;
int b
{
    get
    {
        return _b;
    }
    set
    {
        _b = value;
    }
}

These properties should be created inside a class, but outside a method.

What does this do? When you want to get the value of a, the getter will return _a, the field. When you want to set the value of a, the setter will change the value of both _a and _b, and _b is returned by the getter of b.

Read more about properties here:
MSDN - Properties (C# Programming Guide)[^]
 
Share this answer
 
You could use pointers.

C#
static void Main(string[] args)
      {

          unsafe
          {
              int a = 5;
              int* b = &a;

              a = 10;

              Console.WriteLine("a = {0}, b = {1}", a, *b);
              Console.ReadLine();
          }

      }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900