Skip to content

Instantly share code, notes, and snippets.

@chrisyarbrough
Created February 13, 2021 16:45
Show Gist options
  • Save chrisyarbrough/d49c064fa62e97db97ccb2087eb9f52c to your computer and use it in GitHub Desktop.
Save chrisyarbrough/d49c064fa62e97db97ccb2087eb9f52c to your computer and use it in GitHub Desktop.
Demonstrates how to implement a custom collection initializer by implement the IEnumerable<T> interface and the Add method.
private void OnPresetSelected(object userdata)
{
// We want to quickly define some string collections as "presets".
foreach (var preset in presetsOld)
{
foreach (var prop in preset)
Debug.Log(prop);
}
// But it's much nicer if each collection has a name.
foreach (var preset in presets)
{
foreach (var prop in preset.Properties)
Debug.Log(preset.Name + " " + prop);
}
}
// Jagged arrays are good enough for simple collections, but don't have names.
// Initializing them is pretty sleek though:
private readonly string[][] presetsOld =
{
new[] { "A", "B", "C" },
new[] { "D", "E", "F" }
};
// Our custom data type can be shortened a little:
private readonly Preset[] presetsA =
{
// Object initializer + assigning List with collection initializer:
new Preset("Simple") { Properties = { "A", "B", "C" } },
new Preset("Advanced") { Properties = { "D", "E", "F" } }
};
// But this would be even more concise:
private readonly Preset[] presets =
{
new Preset("Simple") { "A", "B", "C" },
new Preset("Advanced") { "D", "E", "F" }
};
private class Preset : IEnumerable<string>
{
public readonly string Name;
public readonly List<string> Properties;
public Preset(string name)
{
this.Name = name;
this.Properties = new List<string>();
}
public void Add(string property)
=> Properties.Add(property);
public IEnumerator<string> GetEnumerator()
=> Properties.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator()
=> Properties.GetEnumerator();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment