Reputation: 1513
I'm doing an assignment where the I should store some string data in arrays. Each new string should be stored in a separate array, that's why I need a method that returns a new array with a name given from a user. What I want is a new array with a uniq name each time I call this method.
On the 2d line I get an error: A local or parameter named '_arrayNameFromUser' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter test
So how do I create a new array with a user-specified name?
A local or parameter named '_arrayNameFromUser' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter test
static string[] NewArary(string arrayNameFromUser)
{
string[] arrayNameFromUser = new string[2];
return arrayNameFromUser;
}
Upvotes: 0
Views: 235
Reputation: 239674
You've got some confusion here between compile time/runtime. You don't create new variables at runtime.
I suspect that what you need is a Dictionary<string,string[]>
. Then, instead of calling NewArary
(sic), you'd instead do:
Dictionary<string,string[]> arrays = new Dictionary<string,string[]>();
//NewArary("abc");
arrays.Add("abc", new string[]{});
And then later you'd obtain the abc
array by doing:
var thatArray = arrays["abc"];
Upvotes: 2
Reputation: 155175
Give it a different name than the parameter:
static string[] NewArary(string name)
{
string[] ret = new string[2];
ret[0] = name;
return ret;
}
Note that C# naming conventions only use _underscorePrefixed
names for fields, not parameters or locals, and often it's restricted to only static
fields too (as instance fields can be accessed with this.
), see the below example of conventional capitalization of identifiers:
public class TypeName
{
private static readonly String _staticField = "foo";
private Int32 field;
public Int32 Property { get { return this.field; } }
public const String PublicConstant = "bar";
public void Method(Uri parameter) {
Int32 local = 123;
}
}
(Though my use of Int32
instead of int
and String
instead of string
is a controversial stance :D)
Upvotes: 4