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.

2
  • 5
    Also see: stackoverflow.com/questions/13374454/… Commented Oct 29, 2015 at 8: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. Commented Oct 29, 2015 at 8:32

4 Answers 4

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!
Sign up to request clarification or add additional context in comments.

Comments

4

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

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

Comments

2

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

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

Comments

1

You can do:

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

or

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

or

Object x = "hello", 
    y = 22.21;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.