Hashtable : ContainsKey,Contains & Casting a Indexer
//LP : Run as C# Program.
//using System;
//using System.Collections;
/* SUMMARY
• An instance method of hashtable. Assume instance methods are the available-ready-to-go methods whenever you create an instance of an object.
ContainsKey : Called on the Hashtable with the key contents, returns true if key is found.
○ We create a GetHashtable method which creates a hashtable and fills it with values, and returns a hashtable datatype when called.
○ In "main elsewhere" we create a new hashtable instance, by calling theGetHashTable method.
○ We use the ContainsKey property to see if a certain key exists.
○ Or we can just use Contains property to see if a certain key exists.
○ Since the key is a string -- it is not valid to access the indexer, so if the indexer is a string, it needs to be converted to a int.
§ We use a worker variable "value" to store a casting of string "ProtoBot", to a valid int datatype via a cast
○ We output the value of the key.
*/
class Program
{
static Hashtable GetHashtable()
{
Hashtable robohashtable = new Hashtable();
robohashtable.Add("WorkBot", 1000);
robohashtable.Add("CombatBot", 500);
robohashtable.Add("ProtoBot", 250);
return robohashtable;
}
static void Main()
{
Hashtable robohashtable = GetHashtable();
//See if the Hashtable contains this key. Will return true if so.
Console.WriteLine(robohashtable.ContainsKey("CombatBot"));
//Test the Contains method, it works the same way
Console.WriteLine(robohashtable.Contains("ProtoBot"));
//Get value of Protobot with the indexer.
//This is a cast, I assume casting value protobot to
//a numeric value, thus making it a valid indexer.
int value = (int)robohashtable["ProtoBot"];
//Write the value of ProtoBot indexer
Console.WriteLine(value);
}
/*Output
True
True
250
*/
}