Reputation: 1067
string[] aryProp = { "Name", button.Name };
//ListViewItem lvi = new ListViewItem(aryProp);
aryProp={ "Width" , button.Width.ToString() };
" ; expected " (line 3) Why am I getting this error ?
EDIT: @jon , @David , @Grant : Thanks for the help ,But why should I use different syntaxes ? Isn't it kinda illogical ?
Upvotes: 0
Views: 989
Reputation: 170
You are using 1-dimensional array, in your case I suspect you should use 2-dimensional or Dictionary like that:
var aryProp = new Dictionary<string, string>();
aryProp.Add("Name", button.Name);
aryProp.Add("Width", button.Width.ToString());
foreach (var element in aryProp)
{
Console.WriteLine(element.Key + " " + element.Value);
}
Upvotes: 3
Reputation: 1502286
Why am I getting this error ?
Because while your syntax is valid for initialization in a variable declaration, it's not valid for a plain assignment. You can use:
aryProp = new[] { "Width" , button.Width.ToString() };
Or:
aryProp = new string[] { "Width" , button.Width.ToString() };
In specification terms, { ... }
is an array-initializer whereas new string[] { ... }
is an array-creation-expression (which includes an array-initializer, of course). An array-initializer isn't a separate expression you can use as a value; it can only be used in an array-creation-expression, a local-variable-initializer or a variable-initializer.
In non-specification terms: yes, it looks a bit inconsistent, but I suspect there would be significant issues allowing aryProp = { ... }
everywhere, but it's nice to allow it for declarations...
Upvotes: 6