4

In perl I can define a bunch of variables in 1 line:

my value=0;
my (a,b,c)=value;

is there some similar C# way of doing the same? here is what I have:

const bool free = true;
bool t1,t2,t3;

private void Form1_Load(object sender, EventArgs e) {
    //t1,t2,t3=free;
}
2
  • 1
    C# does not support assignment decomposition. Only a single value can be assigned to a single variable with = (although the a=b expression itself yields the value of b). The equivalent is, therefore, multiple assignments. Commented Oct 17, 2013 at 3:47
  • 4
    Side note: please avoid long unrelated text about your fate, opinions and similar other topic not related to your question (including "I'm new here" and "thank you notes") in posts on StackOverflow. Commented Oct 17, 2013 at 4:33

2 Answers 2

6

I believe you can do t1 = t2 = t3 = free; However, it really makes it much harder to read. I would not recommend it.

Sign up to request clarification or add additional context in comments.

2 Comments

Note that this is not equivalent to my (a,b,c)=value or similar constructs as may be found in Perl, Python, Ruby, or Scala which support decomposition during assignment. Rather the same value (e.g. the result of evaluating free) is assigned to all the variables (e.g. t1, t2, t3). With few exceptions (such as in a while or default-value construct) I find this behavior only of moderate use. In C#, t1 = t2 = t3 = value is equivalent to t1 = (t2 = (t3 = value)) as the assignment operator is rightward associative and evaluates to the value assigned but is otherwise not very special.
@user2864740 the phrase is "destructuring assignment"
3

C# does not support full destructuring assignment. Thus, there is no C# equivalent of

my @v = (1,3,5);
my ($a,$b,$c) = @v;

However, as pointed out by @Guthwulf, in the case of a scalar you can write t1 = t2 = t3 = free and it will assign the same value to each element.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.