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

16,921

Solution 1

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
}

Solution 2

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() );
}

Solution 3

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]);

Solution 4

You can use ContainsKey

var dictionary = new Dictionary<string, int>()
{
    {"mac", 1000},
    {"windows", 500}
};

// Use ContainsKey method.
if (dictionary.ContainsKey("mac") == true)
{
    Console.WriteLine(dictionary["mac"]); // <-- Is executed
}

// Use ContainsKey method on another string.
if (dictionary.ContainsKey("acorn"))
{
    Console.WriteLine(false); // <-- Not hit
}
Share:
16,921
sczdavos
Author by

sczdavos

.NET C# Winforms and PHP developer.

Updated on June 17, 2022

Comments

  • sczdavos
    sczdavos almost 2 years

    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#?