Can I assign each value in an array to separate variables in one line in C#? Here's an example in Ruby code of what I want:
irb(main):001:0> str1, str2 = ["hey", "now"]
=> ["hey", "now"]
irb(main):002:0> str1
=> "hey"
irb(main):003:0> str2
=> "now"
I'm not sure if what I'm wanting is possible in C#.
Edit: for those suggesting I just assign the strings "hey" and "now" to variables, that's not what I want. Imagine the following:
irb(main):004:0> val1, val2 = get_two_values()
=> ["hey", "now"]
irb(main):005:0> val1
=> "hey"
irb(main):006:0> val2
=> "now"
Now the fact that the method get_two_values
returned strings "hey" and "now" is arbitrary. In fact it could return any two values, they don't even have to be strings.
Update: In C#7 you can easily assign multiple variables at once using tuples. In order to assign array elements to variables, you'd need to write an appropriate
Deconstruct()
extension methods:Old answer:
In fact, you can achieve similar functionality in C# by using extension methods like this (note: I haven't include checking if arguments are valid):
And you can use them like this:
In case a return value from a function is needed, the following overload would work:
In this way:
You avoid having to repeat array name like in solution proposed by JaredPar and others; the list of "variables" is easy to read.
You avoid having to explicitly declare variables types like in Daniel Earwicker's solution.
The disadvantage is that you end up with additional code block, but I think it's worth it. You can use code snippets in order to avoid typing braces etc. manually.
I know it's a 7 years old question, but not so long time ago I needed such a solution - easy giving names to array elements passed into the method (no, using classes/structs instead of arrays wasn't practical, because for same arrays I could need different element names in different methods) and unfortunately I ended up with code like this:
Now I could write (in fact, I've refactored one of those methods right now!):
My solution is similar to pattern matching in F# and I was inspired by this answer: https://stackoverflow.com/a/2321922/6659843
No, but you can initialize an array of strings:
Although that's probably not too useful for you. Frankly its not hard to put them on two lines: