C# setter/getter of two variables

4.1k Views Asked by At

Is there an option to do one setter/getter for two variables? Or the only option are two separate setter/getter's like this:

int var1;
int var2;

public int var1 
    {
    get { return var1; }
    set { var1 = value; }
    }

public int var2 
    {
    get { return var2; }
    set { var2 = value; }
    }
2

There are 2 best solutions below

0
On BEST ANSWER

You can try this

public int var1 { get;set;}

public int var2 { get;set;}
0
On

"one setter/getter for two variables" - there no syntax to simplify that (you can use automatic properties for single value only).

It can be implemented with wrapping these variables into class and using single property to get/set. I.e. using built in Tuple class:

var1;
int var2;

public Tuple<int,int> BothVars
{
  get { return Tuple.Create(var1,var2); }
  set { 
       var1 = value.Item1;
       var2 = value.Item2;
      }
}