user222427
user222427

Reputation:

How to HardCode a string array?

I basically want to type in a string[] and and be able to do a foreach based on newline. I tried like this but I dont believe this works.

static string[] mystrings = {"here"+
"there"+
"mine"
}

and I want to foreach it and get back one at a time. Is this possible?

Upvotes: 5

Views: 18723

Answers (3)

Joshua Honig
Joshua Honig

Reputation: 13215

You just have to add new[] or new string[] in front of the curly-brace list. And use commas, not plus signs. As in

string[] mystrings = new[] { "here", "there", "mine" };

FYI, the new[] shortcut is syntactic sugar provided by C#, which infers that you specifically mean new string[]. If you are creating an array of mixed types (such as an array of object), you will have to explicitly use new object[], because otherwise the C# compiler won't know which type you are implying. That is:

// Doesn't work, even though assigning to variable of type object[]
object[] myArgs = new[] { '\u1234', 9, "word", new { Name = "Bob" } };

// Works
object[] myArgs = new object[] { '\u1234', 9, "word", new { Name = "Bob" } };

// Or, as Jeff pointed out, this also works -- it's still commas, though!
object[] myArgs = { '\u1234', 9, "word", new { Name = "Bob" } };

// ...althouth this does not, since there is not indication of type at all
var myArgs = { '\u1234', 9, "word", new { Name = "Bob" } };

Upvotes: 14

sll
sll

Reputation: 62504

static string[] items = new[] { "here", "there", "mine" };

and then

foreach (string item in items)
{
   System.Diagnostics.Debug.WriteLine(item);
}

But keep in mind that arrays can be initialized once and then you can not add more items, I would suggets using generic list List<string> instead.

IList<string> items = new List<string> { "one", "two", "three" };

Upvotes: 0

brpyne
brpyne

Reputation: 1006

static string[] myStrings = new string[] { "one", "two", "three" };

foreach(string s in myStrings)
{
     Console.WriteLine(s);
}

Upvotes: 1

Related Questions