2

i was searching if there's a way to initialize multiple variables with different values on the same line, same as you can do in JavaScript. (maybe in c# 6 ?)

for example:

var x = "hello", 
    y = "friend";

** EDIT

I know i can assign with the same value (seen other posts on SO as well - i don't see how this post is duplicated ) i would like it to be with different values (using the var key word). as i see from the answers below i see there's no way without explicitly declare the type. so thanks for the help.

Sagiv b.g
  • 28,620
  • 8
  • 59
  • 91
  • 5
    Also see: http://stackoverflow.com/questions/13374454/declare-and-assign-multiple-string-variables-at-the-same-time – Juho Rutila Oct 29 '15 at 08:26
  • Oh sorry I must have used an older version where you couldn't use them in single line. Or maybe it was VB.NET Please ignore my answer. – Sorrel Vesper Oct 29 '15 at 08:32

4 Answers4

5

just assign like that:

string str = "1", str1="2", str3="3", str4="4", str5="5";

please, remember, that implicitly-typed local variables cannot have multiple declarations so this code will not be compiled:

var someVar1 = "1", someVar2 = "2", someVar3 = "3", someVar4 = "4", someVar5 = "5";//This line is error and is not compiled!
StepUp
  • 30,747
  • 12
  • 76
  • 133
4

Implicitly-typed variables cannot have multiple declarators. You have to specify the type.

string x = "hello", 
       y = "friend";
vincentp
  • 1,365
  • 8
  • 12
2

You can, but only if you don't use var:

string x = "hello", y = "friend";
user1793963
  • 1,205
  • 1
  • 12
  • 24
1

You can do:

String x = "hello", 
    y = "friend";

or

Object x = "hello", 
    y = "friend";

or

Object x = "hello", 
    y = 22.21;
Kajal Sinha
  • 1,504
  • 10
  • 17