I've used ReSharper to convert the function to Linq statements which may help some people understand what's going (or just confuse people even more).
public string tostrLinq(int n)
{
return string.Concat(n--, "").Aggregate("", (string current, char c) => current + c);
}
As others have already stated, basically the inputted int
is concatenated with an empty string
which basically gives you a string representation of the the int
. As string
implements IEnumerable
, the foreach
loop breaks up the string into a char[]
, giving each character of the string on each iteration. The loop body just then joins the characters back together as a string through concatenating each char
.
So for example, given input of 5423
, it gets converted to "5423"
, and then broken up into "5"
, "4"
, "2"
, "3"
and finally stitched back to "5423"
.
Now the part that really hurt my head for a while was the n--
. If this decrements the int
, then why don't we get "5422"
returned instead? This wasn't clear to me until after I read the MSDN Article: Increment (++) and Decrement (--) Operators
The increment and decrement operators are used as a shortcut to modify
the value stored in a variable and access that value. Either operator
may be used in a prefix or postfix syntax.
If | Equivalent Action | Return value
=====================================
++variable | variable += 1 | value of variable after incrementing
variable++ | variable += 1 | value of variable before incrementing
--variable | variable -= 1 | value of variable after decrementing
variable-- | variable -= 1 | value of variable before decrementing
So because the decrement operator is applied at the end to n
, the value of n
is read and used by string.Concat
before n
is decremented by 1.
I.e. string.Concat(n--,"")
is going to give the same output as string.Contact(n, ""); n = n - 1;
.
So to get "5422"
we would change it to string.Concat(--n, "")
so that n
is decrement first before it is passed to string.Contact
.
TL;DR; The function is a round about way of doing n.ToString()
Interestingly, I also used ReSharper to convert it to a for
loop but the function no longer works as n
is decremented on each iteration of the for loop, unlike the foreach
loop:
public string tostrFor(int n)
{
string s = "";
for (int index = 0; index < string.Concat(n--, "").Length; index++)
{
char c = string.Concat(n--, "")[index];
s = s + c;
}
return s;
}