One of the things that I love about C# is how so many of it's features are just very conveniently designed compiler tricks. This means that, just like any other magic trick, once you know how the trick is performed you immediately realize that there really is nothing magical about it.
So, let's talk about default parameters. They are actually just constant values that get compiled into your code when you go to use a method that has them. Let's look at an example...
The Code
public enum Country
{
US,
CA
}
public static class SharedUtility
{
public static bool CanDrink(
int age,
Country country = Country.CA)
{
switch (country)
{
case Country.US:
return age >= 21;
case Country.CA:
return age >= 18;
default:
throw new ArgumentException(
"Invalid Country",
nameof(country));
}
}
}
public class SharedUtilityTests
{
[Fact]
public void CanDrink()
{
var result = SharedUtility.CanDrink(20);
// The line above will compile into the following:
// var result = SharedUtility.CanDrink(20, Country.CA);
// Thus, the Assert below will succeed!
Assert.True(result, "The default was not US!");
}
}
So, now that you know how the trick is performed, how could this cause a problem for you? Specifically, what happens if you update a library that exposes methods with default parameters?
Nothing will change, until you recompile against the library!
If another library changes their default parameters, but you do not recompile your code against it, then your code will be using the old default values! Let's look back at the previous example and see why this could cause confusion...
The Change
public enum Country
{
US,
CA
}
public static class SharedUtility
{
public static bool CanDrink(
int age,
// NOTE: We have changed the default value!
Country country = Country.US)
{
switch (country)
{
case Country.US:
return age >= 21;
case Country.CA:
return age >= 18;
default:
throw new ArgumentException(
"Invalid Country",
nameof(country));
}
}
}
public class SharedUtilityTests
{
[Fact]
public void CanDrink()
{
var result = SharedUtility.CanDrink(20);
// If you do NOT recompile and just replace the DLL,
// then this test will still pass. However, as soon
// as you recompile this test will start failing!
Assert.True(result, "The default was not US!");
}
}
Don't take my word for it, here are screenshots of that code in action...
Enjoy,
Tom
No comments:
Post a Comment