String as Indexer in C# -
let me start showing code:
using system; namespace tutorialadvanced { class collection { object[] values; public collection(int size) { values = new object[size]; } public object this[string index] { { return values[index]; } set { values[index] = (object)value; } } } class program { static void main() { collection collection = new collection(3); collection["integer"] = 123; collection["decimal"] = 456.78; collection["text"] = "hello world!"; double total = (double)(int)collection["integer"] + (double)collection["decimal"]; console.writeline("total {0}", total); console.writeline(); collection collection2 = new collection(2); collection2["integer"] = 123; collection2["decimal"] = 456.78; collection2["text"] = "hello world!"; // wont added because of limit } } }
i'm doing tutorial, , class program
given me, , can't modify it. need create collection
class, collection
class made me. there problem indexer
, because string
doesn't seem work same way integer indexers worked in previous tutorials. there way use string indexer, or should consider different approach? adding namespaces not allowed. have been stuck in tutorial week now.
you can use dictionary collection:
dictionary<string, object> dict = new dictionary<string, object>(); dict["hello"] = "world";
Comments
Post a Comment