Skip to content

Instantly share code, notes, and snippets.

@sometowngeek
Last active February 24, 2018 18:35
Show Gist options
  • Save sometowngeek/285ddf417f65ef7499232c204be20f3b to your computer and use it in GitHub Desktop.
Save sometowngeek/285ddf417f65ef7499232c204be20f3b to your computer and use it in GitHub Desktop.
Indexer Example
public class AnObject
{
public int Id { get; set; }
public string Name { get; set; }
public AnObject(int id, string name)
{
this.Id = id;
this.Name = name;
}
public AnObject()
{
}
public string Play()
{
return "I played!";
}
}
public class Class1
{
public static void Main(String[] args)
{
TheObjects objs = new TheObjects();
objs.Add(new AnObject(1, "Name"));
Console.WriteLine(objs.ToString());
Console.ReadKey();
}
}
public class TheObjects
{
public AnObject[] objects = new AnObject[2];
private int size = 0;
public TheObjects()
{
}
public override string ToString()
{
return String.Format("{0}: {1}; {2}", this[0].Id, this[0].Name, this[0].Play());
}
public void Add(AnObject obj)
{
if (this.size == objects.Length)
throw new IndexOutOfRangeException();
objects[this.size] = obj;
}
public AnObject this[int index]
{
get
{
return objects[index];
}
set
{
objects[index] = value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment