Checking an array variable in C# vs JavaScript

I’m new to Unity and C# (I must learn C# to work with some people), but the best tutorials guiding from basics to game creation I’ve found only cover JavaScript, so I’ve been following along, translating JavaScript to C# where needed.

When it came time to create an IF statement checking on an item in a string array, I ran into a problem. The JavaScript code works like this:

	var inventory = Array("food", "gun", "ammo");
	if ("food" in inventory)
		print("You have found " + inventory[0]); 

The closest equivalent I could find (most resources are full of technical terms I don’t yet understand) is C#'s “foreach,” which looks like this:

string[] inventory = {"food", "gun", "ammo"};
	foreach(string myItems in inventory)
		{
		if(myItems == "food")
			print("You have found " + inventory[0]);
		}

Is that a suitable way to do it? I heard that foreach is a loop (not sure if the JavaScript use of “in” is too), so I wasn’t sure if that meant it just keeps going on and on in the background, taking up resources or something else inefficient. All I wanted to do at the moment was check on a string in an array.

The misconception here is because in JavaScript Object and Array don’t differ much. The later has length property but you can interchange them freely. In c# Arrays are more like good old arrays in C. But they have lots of extending methods like IndexOf for example. They are basically doing the same as your code does internally but at least your code gets cleaner.

Also you may want to look at 3 and Dictionary types. Which are more powerful and have better search time than arrays.

string inventory = {“food”, “gun”, “ammo”};
foreach(string item in inventory)
if(item == “food”)
print("You have found " + item);

item carries the value of the current item from the inventory collection. This is suitable for display as it is just a string.

If you use Lists with System.Linq you can do searches like this myList.Where(item => item == “food”);

I’m sure it adds some overhead, but might be worth it.