Skip to content

Instantly share code, notes, and snippets.

@ScottLilly
Last active December 17, 2019 07:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ScottLilly/717fba395154c445237011058c809c5b to your computer and use it in GitHub Desktop.
Save ScottLilly/717fba395154c445237011058c809c5b to your computer and use it in GitHub Desktop.
Passing List variable as a parameter
void Main()
{
// I don't like this variable. It has a very short "life"
List<string> monsterThings = new List<string>();
monsterThings.Add("Thing 1");
monsterThings.Add("Thing 2");
monsterThings.Add("Thing 3");
Monster myMonster = new Monster("Snake", monsterThings);
}
// My preference
void Main2()
{
Monster myMonster = new Monster("Snake");
myMonster.Things.Add("Thing 1");
myMonster.Things.Add("Thing 2");
myMonster.Things.Add("Thing 3");
}
// My real preference
void Main3()
{
Monster myMonster = new Monster("Snake");
myMonster.AddThing("Thing 1");
myMonster.AddThing("Thing 2");
myMonster.AddThing("Thing 3");
}
public class Monster
{
public string Name { get; set;}
public List<string> Things {get; set;}
public Monster(string name, List<string> things)
{
Name = name;
Things = things;
}
// My preference
public Monster(string name)
{
Name = name;
Things = new List<string>();
}
// Even better - so we can potentially add more code to do things like
// 1. Ensure this isn't a duplicate "thing"
// 2. Only allow "thing" values that contain letters (and not numbers)
// 3. Raise other event notifications
public void AddThing(string thing)
{
Things.Add(thing);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment