I have a piece of code similar to this
public string GetMessage()
{
if (new Random().Next(10) % 2 == 0 == 0)
{
string message = "bad luck";
return message;
}
string message = "lucky";
return message;
}
This code could surely be improved, but what's puzzling me is that it unexpectedly produces the error
A local or parameter named 'message' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
Now what's weird about this is that the variable in the smaller scope shouldn't even exist to cause the clash. It's legal in C:
char* GetMessage()
{
if (rand() % 2 == 0)
{
char* message = "bad luck";
return message;
}
char* message = "lucky";
return message;
}
This compiles and works. As soon as the smaller scope ends, the variable inside of it ceases to exist and I'm free to reuse the name. Similar code also works in Swift, so why is this different in C#?