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
Cheers!