David Shifflet's Snippets

Mindset + Skillset + Toolkit = Success




< Back to Index

Code This, Not That - Use Params

So let's say we had animals and we wanted to write their sounds out to the console.

Let's start with a class like:

public class Animal
{
	public string Sound { get; set; }
}
And let's create a service to make an animal speak:
public class ThatAnimalSpeakingService
{
	public void Speak(Animal animal)
	{
		Console.WriteLine(animal.Sound);
	}
}
And now for a test with multiple animals...
[TestMethod]
public void ThatMakeAnimalsSpeak()
{
	var cat = new Animal() { Sound = "meow"};
	var dog = new Animal() { Sound = "woof" };
	var fish = new Animal() { Sound = "bloop" };
	
	var svc = new ThatAnimalSpeakingService();
	svc.Speak(cat);
	svc.Speak(dog);
	svc.Speak(fish);
}
And that works we get:
meow
woof
bloop
The only problem is the service can only take one animal at a time. What if we wanted to deal with one animal or an array of animals?

Enter "params"

Let's create a new service:
public class ThisAnimalSpeakingService
{
	public void Speak(params Animal[] animals)
	{
		foreach (var animal in animals)
		{
			Console.WriteLine(animal.Sound);
		}
	}
}
(We called them This and That because it's code THIS not THAT!) Now we can do something in a test like:
[TestMethod]
public void ThisMakeAnimalsSpeak()
{
	var cat = new Animal() { Sound = "meow" };
	var dog = new Animal() { Sound = "woof" };
	var fish = new Animal() { Sound = "bloop" };

	var svc = new ThisAnimalSpeakingService();
	//We can still do...
	svc.Speak(cat);

	//We can now do...
	svc.Speak(cat, dog, fish);

	//and we can also do an array...
	var arrayOfAnimals = new [] {cat, dog, fish};
	svc.Speak(arrayOfAnimals);
}
A lot more flexibility with out a lot more code! Instead of dealing with one thing, be able to deal with many things!

Learn more about "params" by clicking here!