initializing an array in C#

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello everyone,

I want to put values inside array in if statement. so I declared an array

string[] ar = new ar[5];


if (x=="10)
ar={"c", "d", "e","f"}
else
ar={"a", "b", "c","d"}

this gives me an error Invalid expression term "{"

can anyone tell me what am I doing wrong.
 
[...]
if (x=="10)
ar={"c", "d", "e","f"}
else
ar={"a", "b", "c","d"}

this gives me an error Invalid expression term "{"

can anyone tell me what am I doing wrong.

Try:

if (x=="10)
ar= new string[] {"c", "d", "e","f"};
else
ar=new string[] {"a", "b", "c","d"};

Note the addition of the "new" operator, along with semicolons.

Pete
 
Vinki,

This syntax isn't available until C# 3.0. The only way you will get
this to work is if you are using VS.NET Orcas (which is currently in beta
right now).
 
Nicholas Paldino said:
Vinki,

This syntax isn't available until C# 3.0. The only way you will get
this to work is if you are using VS.NET Orcas (which is currently in beta
right now).


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Vinki said:
Hello everyone,

I want to put values inside array in if statement. so I declared an
array

string[] ar = new ar[5];


if (x=="10)
ar={"c", "d", "e","f"}
else
ar={"a", "b", "c","d"}

this gives me an error Invalid expression term "{"

can anyone tell me what am I doing wrong.

Yeah, but using the new keyword, it will work in any version :)

ar = new string[] { "c", "d", "e", "f" };

Also, there is an error in the if statement...missing a quote:

if (x == "10") ...

Lastly, these are all chars in the example so the OP may want to declare the
array as a character array instead of string...:

char[] ar;
if (x == "10") {
ar = new char[] { 'c', 'd', 'e', 'f' };
} else {
ar = new char[] { 'a', 'b', 'd', 'e' };
}

HTH,
Mythran
 
Back
Top