bryanlekhoa
bryanlekhoa

Reputation: 21

Is there anyway to increase multiple variables with same value in a single statement

I wanna increase multiple variables with same value, like this:

A += 2;
B += 2;
C += 2;

But in a single statement.

I've already tried:

A += B += C =+ 2;

But it's wrong. This stack "2" many times. Is there any way to do that?

Upvotes: 2

Views: 892

Answers (2)

TheGeneral
TheGeneral

Reputation: 81493

This is completely nonsensical and has little real world value, but you could use pointers and unsafe

static unsafe void Mutate(int*[] ary, Func<int,int> func)
{
   foreach (var item in ary)
      *item = func(*item);
}
static unsafe void Main(string[] args)
{
   var a = 0;
   var b = 0;
   var c = 0;

   var ary = new [] { &a, &b,&c};
   Mutate(ary, x => x + 2);

   Console.WriteLine(a);
}

Output

2

or

static unsafe void Mutate(Func<int, int> func, params int*[] array )
{
   foreach (var item in array)
      *item = func(*item);
}

...

Mutate(x => x + 2, &a, &b, &c);
Console.WriteLine(a);

or

public static class Extensions
{
   public static unsafe void Mutate( this int*[] array, Func<int, int> func)
   {
      foreach (var item in array)
         *item = func(*item);
   }
}

...

var list = new  [] { &a, &b,&c};
list.Mutate(x => x + 2);
Console.WriteLine(a);

Upvotes: 0

Peter Duniho
Peter Duniho

Reputation: 70652

No, there is no such syntax in C# to do that.

You can, of course, put all of the increment operations on a single line:

A += 2; B += 2; C += 2;

But that's not really what you're asking for.

I will point out that, if you find this to be a common pattern in your code — common enough that you feel there ought to be a special syntax in the language to support it — you are probably overlooking an opportunity to define a new type, probably a struct, to represent the triplet values you're finding yourself adjusting uniformly on a regular basis.

For example, you might have something like this:

struct MyStruct
{
    public int A { get; }
    public int B { get; }
    public int C { get; }

    public MyStruct(int a, int b, int c)
    {
        A = a;
        B = b;
        C = c;
    }

    public static MyStruct operator +(MyStruct v, int i)
    {
        return new MyStruct(v.A + i, v.B + i, v.C + i);
    }
}

which you could then use like this:

MyStruct v = new MyStruct(1, 2, 3);

v += 2;
// v.A is now 3, v.B is now 4, v.C is now 5

Upvotes: 3

Related Questions