String as Indexer in C#
Let me start by showing the code:
using System;
namespace TutorialAdvanced
{
class Collection
{
object[] values;
public Collection(int size)
{
values = new object[size];
}
public object this[string index]
{
get
{
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 is {0}", total);
Console.WriteLine();
Collection collection2 = new Collection(2);
collection2["integer"] = 123;
collection2["decimal"] = 456.78;
collection2["text"] = "Hello World!"; // This wont be added
because of limit
}
}
}
I'm doing this tutorial, and class Program was already given to me, and I
can't modify it. What I need to do is to create Collection class, so
Collection class is made by me. But there is this problem with Indexer,
because it is string it doesn't seem to work the same way integer Indexers
worked in previous tutorials. Is there a way to use string as Indexer, or
should I consider different approach? Also adding namespaces are not
allowed. I have been stuck in this tutorial for a week now.
No comments:
Post a Comment