-4

It's easier if I just state that in this:

public static void GetObstacles(params string[] ObstacleLayers)
{
    foreach (string Layer in ObstacleLayers)
    {
        var Layer = _tiledMap.GetLayer<TiledMapTileLayer>(Layer);
    }
}

I want the created variable var Layer to be named after the string Layer.

ErikHeemskerk
  • 1,623
  • 14
  • 30
  • 4
    why do you care for names of variables? Just name the string-variable `layerName`, and the `TiledMapTileLayer`-variable `layer`. – MakePeaceGreatAgain Jan 07 '21 at 09:29
  • 4
    You cannot -- this is forbidden by the language – canton7 Jan 07 '21 at 09:29
  • You just have to be a bit more careful when naming variables, perhaps `foreach (string Layer in ObstacleLayers)` could have been `foreach (string obstacleLayer in ObstacleLayers)` – phuzi Jan 07 '21 at 09:32
  • 2
    _"I want the created variable var Layer to be named after the string Layer"_ Think about what happens when you do something like `Console.WriteLine(Layer.GetType().Name);`, for example. – 41686d6564 stands w. Palestine Jan 07 '21 at 09:32
  • 2
    Are you looking for a `Dictionary`? You don't create new *variables* whilst your code is running. – Damien_The_Unbeliever Jan 07 '21 at 09:37
  • related https://stackoverflow.com/questions/4649947/why-doesnt-c-sharp-allow-me-to-use-the-same-variable-name-in-different-scopes – Drag and Drop Jan 07 '21 at 09:51
  • "_It is an error for the local variable declaration space of a block and a nested local variable declaration space to contain elements with the same name. Thus, within a nested declaration space it is not possible to declare a local variable or constant with the same name as a local variable or constant in an enclosing declaration space_" from C# Language Specification, secssion 3.3, page 57. – Drag and Drop Jan 07 '21 at 09:54
  • Easily set: give **different** things a **different** name. Your string surely is something different then the tilelayer, isn´t it? A name of a variable should always determine its purpose. How would you differentiate between a layer and a layer, if using the same name for different things was possible? – MakePeaceGreatAgain Jan 07 '21 at 11:43

1 Answers1

0

The thing you ask for is as if you were asking for designate a cat as a dog the same time like in a schrodinger box.

However, you have the notion of dynamic but this does not apply to foreach because you can't assign the iteratored var and here the goal is not to modulate it.

Therefore you need to write:

foreach (string layerName in ObstacleLayers)
{
  var layer = _tiledMap.GetLayer<TiledMapTileLayer>(layerName);
  // do something with the layer
}

So the string element you iterate over from the collection is used to get an object instance of type Layer (perhaps) to work on.

It seems that you did not understand or learned what are loops and variables and their usage as well as scope.