How do I use C# generic Dictionary like the Hashtable is used in Java? -
i following tutorial , working dictionary have found out equivalent hashtable in java.
i created dictionary so:
private dictionary<string, tile> tiles = new dictionary<string, tile>(); though dilemma when using dictionary can not use get, written in java so:
tile tile = tiles.get(x + ":" + y); how accomplish same thing. meaning getting x:y result?
short answer
use indexer or trygetvalue() method. if key isn't present, former throws keynotfoundexception , latter returns false.
there no direct equivalent java hashtable get() method. that's because java's get() returns null if key isn't present.
returns value specified key mapped, or null if map contains no mapping key.
on other hand, in c# can map key null value. if either indexer or trygetvalue() says value associated key null, doesn't mean key isn't mapped. means key mapped null.
running example:
using system; using system.collections.generic; public class program { private static dictionary<string, tile> tiles = new dictionary<string, tile>(); public static void main() { // add 2 items dictionary tiles.add("x", new tile { name = "y" }); tiles.add("x:null", null); // indexer access var value1 = tiles["x"]; console.writeline(value1.name); // trygetvalue access tile value2; tiles.trygetvalue("x", out value2); console.writeline(value2.name); // indexer access of null value var value3 = tiles["x:null"]; console.writeline(value3 == null); // trygetvalue access null value tile value4; tiles.trygetvalue("x:null", out value4); console.writeline(value4 == null); // indexer access key not present try { var n1 = tiles["nope"]; } catch(keynotfoundexception e) { console.writeline(e.message); } // trygetvalue access key not present tile n2; var result = tiles.trygetvalue("nope", out n2); console.writeline(result); console.writeline(n2 == null); } public class tile { public string name { get; set; } } }
Comments
Post a Comment