Search code examples
c#arraysdynamic-arrays

Is there a C# equivalent of PHP's array_key_exists?


Does C# have any equivalent of PHP's array_key_exists function?

For example, I have this PHP code:

$array = array();
$array[5] = 4;
$array[7] = 8;
if (array_key_exists($array, 2))
    echo $array[2];

How would I turn this into C#?


Solution

  • 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
    }