Happyam

I am who I am
  • Home
  • About
3 Nov 2009

PHP String Literal Array Key in C#

PHP allow us to use String Literal as an Array Key, which is very handy in some situation.

<?php
$happyArray = array(4 => 5, 9 => 12, "happyam" => 30);

echo $happyArray [4]; // 5
echo $happyArray[9]; // 12
echo $happyArray["happyam"]; // 30

?> 

We can perform similar operation using a HashTable in C#

Hashtable ht = new Hashtable();

ht.Add(4,5);
ht.Add(9,12);
ht.Add("happyam", 30);

document.write(ht[4]);  // 5
document.write(ht[9]);  // 12
document.write(ht["happyam"]);  // 30

You can also use Dictionary if your Keys had the same data type, which is more efficient.  For example:

using System.Collections.Generic; // Dictionary object is in System.Collections.Generic

Dictionary<string, int> dic = new Dictionary<string, int>();
dic.Add("Jacky", 30);
dic.Add("Minnie", 26);
dic.Add("Happyam", 35);
document.write(dic["Jacky"]);  // 30
document.write(dic["Minnie]);  // 26
document.write(dic["happyam"]);  // 35
3 November, 2009 at 9:39 by Happyam

Posted in Programming | 1 Comment »

  • June 2025
    M T W T F S S
    « Nov    
     1
    2345678
    9101112131415
    16171819202122
    23242526272829
    30  
  • Recent Posts

    • PHP String Literal Array Key in C#
  • Recent Comments

    • Brandon Suchecki on PHP String Literal Array Key in C#
  • Categories

    • Programming
  • Archives

    • November 2009
  • Tags

    Test
Happyam is proudly powered by WordPress
Design & code by Jonk
Entries (RSS) and Comments (RSS).