Is there a C# equivalent of PHP's array_key_exists?
Sorry, but dynamic arrays like PHP are not supported in C#. What you can do it create a Dictionary<TKey, TValue>(int, int) and add using .Add(int, int)
using System.Collections.Generic;...Dictionary<int, int> dict = new Dictionary<int, int>();dict.Add(5, 4);dict.Add(7, 8);if (dict.ContainsKey(5)){ // [5, int] exists int outval = dict[5]; // outval now contains 4}
An array in C# has a fixed size, so you would declare an array of 8 integers
int[] array = new int[8];
You then only need to check the length
if(array.Length > 2){ Debug.WriteLine( array[2] );}
That's fine for value types, but if you have an array of reference types, e.g.
Person[] array = new Person[8];
then you'll need to check for null as in
if(array.Length > 2 && array[2] != null){ Debug.WriteLine( array[2].ToString() );}
In C# when you declare a new array, you have to provide it a size for memory allocation. If you're creating an array of int
, values are pre-populated at instantiation, so the keys will always exist.
int[] array = new int[10];Console.WriteLine(array[0]); //outputs 0.
If you want a dynamically sized array, you can use a List
.
List<int> array = new List<int>array.push(0);if (array.Length > 5) Console.WriteLine(array[5]);