Skip to content

Instantly share code, notes, and snippets.

@chrisyarbrough
Created February 13, 2021 16:14
Show Gist options
  • Save chrisyarbrough/287bfe1f131977fecb456bc9f13bc739 to your computer and use it in GitHub Desktop.
Save chrisyarbrough/287bfe1f131977fecb456bc9f13bc739 to your computer and use it in GitHub Desktop.
Demonstrates how not to use C# a collection initializer to assign fields within the object initializer.
/// <summary>
/// Creates beings imbued with magical powers.
/// </summary>
public class WizardFactory
{
public Wizard Create()
{
// Just imagine this as part of some editor interface
// or default values that are hardcoded for any reason.
return new Wizard
{
// This is Object Initializer syntax instead of writing
// var wizard = new Wizard();
// wizard.Name = "Gandalf";
Name = "Gandalf",
// This is Collection Initializer syntax and lets
// us setup a dictionary with key-value pairs.
SimpleSpells = new Dictionary<string, string>
{
{ "Light", "Light of Moria" },
{ "Mind Reading", "Power of the Maiar" },
},
// For arrays, we don't even have to specify the type. Sweet!
HatStyles = new[] { "Merlin", "Dumbledore", "Dresden" },
// So, let's try to get rid of the Dictionary types as well:
// Yes, this compiles!
AdvancedSpells =
{
{ "Balrog Blocking", "You shall not pass!" },
{ "Endurance", "Surviving the fall" }
},
// Wait, no. NullReferenceException at runtime.
// Collection initializers do not create collections, they
// only call Add on existing instances of collections.
};
}
public class Wizard
{
public string Name;
public string[] HatStyles;
public Dictionary<string, string> SimpleSpells;
public Dictionary<string, string> AdvancedSpells;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment