-3

How can i declare a variable inside String.format and use it again like :

String.Format("{0} {1}", int t = 1, new string[] { "a", "b" }.ElementAt(t));

update
I just want to learn something new and type the code in one line.
It is not necessary in this case, but useful in others.

update
I found another solution :

int indx;
var st = String.Format("{0} {1}", (indx=1), new string[] { "a", "b" }.ElementAt(indx));
Ahmed Aljaff
  • 149
  • 2
  • 10
  • 2
    What's the need for doing this? You can always declare the variable outside of string.Format and use the value inside string.Format. – Kosala W Jan 16 '16 at 22:38
  • 1
    is there a reason you think this would be a good idea? – user1666620 Jan 16 '16 at 22:40
  • Thank you for your comments. I just want to learn something new and type the code in one line. It is not necessary in this case, but used in other cases. – Ahmed Aljaff Jan 17 '16 at 11:13

2 Answers2

1

It would be good if you would share reason why you try to do it this way, and maybe tell us what are you working on.

Your code to work should look like this

int t = 1;
string[] myArray = new string[] { "a", "b" };
Console.WriteLine(string.Format("{0} {1}", t, myArray[t]));

What you are attempting to do seems to be without any sense, first of all it will not work. Doing stuff your way makes it impossible to access t and array you created and even if it worked it would be same as static string string myString = "1 b". Your way you make it impossible to manipulate these variables because they would only exist in context of that one line and would be back to their initial value when it gets executed each time.

MoreThanChaos
  • 2,054
  • 5
  • 20
  • 40
  • Thank you for your comment. I just want to learn something new and type the code in one line. It is not necessary in this case, but used in other cases. – Ahmed Aljaff Jan 17 '16 at 11:15
1

It is not possible. Consider string.format as a method with few overloads, which takes few set of parameters as mentioned in MSDN link. Your way of calling the method does not satisfy your intent hence it would fail. I don't understand any reason why you would try to do something like this.

Ankit Vijay
  • 3,752
  • 4
  • 30
  • 53
  • Thank you for your comment. I just want to learn something new and type the code in one line. It is not necessary in this case, but used in other cases. – Ahmed Aljaff Jan 17 '16 at 11:15