-
-
Save ScottLilly/717fba395154c445237011058c809c5b to your computer and use it in GitHub Desktop.
Passing List variable as a parameter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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