Dangers of Using Optional Parameters In .NET C#
top of page

Subscribe to get best practices, tutorials, and many other cool things directly to your email inbox

  • Writer's pictureAhmed Tarek

Dangers of Using Optional Parameters In .NET C#

Updated: Apr 17

When to be cautious while using Optional Parameters in .NET C#


Method Optional Parameters Issue Problem .NET C# DotNet CSharp Code Coding Programming Software Design Development Engineering Architecture Best Practice Ahmed Tarek
Why To Be Cautious When Using Optional Parameters In .NET C#. Images by gstudioimagen and pch.vector on Freepik and adjusted by Ahmed Tarek

We all know about Optional Parameters and we love to use them instead of defining too many method overloads.


However, there is something important that you need to keep in mind while using Optional Parameters especially if you are developing your own class library.


In this article, I will show you something that could blow your mind.


 

Method Optional Parameters Issue Problem .NET C# DotNet CSharp Code Coding Programming Software Design Development Engineering Architecture Best Practice Ahmed Tarek
Brain Teaser. Image by Ahmed Tarek

Brain Teaser


Let’s first show you the problem by example.


You started the development phase of your software system. Regardless of what the system actually does, assume that your system needs to do some mathematical operations.


Instead of creating your own mathematical library, you decided to use a well-known third-party library. Good choice.


Now, for the sake of demonstration, we would write the library ourselves and keep it in the same solution. However, in real life, it is expected that you don’t own the library and it could be delivered as a Nuget package or even a DLL to reference in your project.


So, starting from this point, we would create our solution as in the image below:


Method Optional Parameters Issue Problem .NET C# DotNet CSharp Code Coding Programming Software Design Development Engineering Architecture Best Practice Ahmed Tarek
Solution structure. Image by Ahmed Tarek

In the ThirdPartyLibrary project, we have only one class; the Calculator class.


The code inside this class is so simple as follows:


using System;

namespace ThirdPartyLibrary
{
    public static class Calculator
    {
        public static int Add(int a = 0, int b = 0)
        {
            Console.WriteLine($"Add => a: {a}, b: {b}");
            return a + b;
        }

        public static int Multiply(int a, int b = 0)
        {
            Console.WriteLine($"Multiply => a: {a}, b: {b}");
            return a * b;
        }
    }
}

As you can notice, we have two simple methods with some optional parameters.


We are also writing to the console the values of the passed-in parameters to be used for demonstration.


Now, moving to the OptionalParameters project. Assume that this is your actual software system project.


The project has only one class which is the Program class.


The code inside this class is as follows:


using System;
using ThirdPartyLibrary;

namespace OptionalParameters
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int additionResult = Calculator.Add();
            additionResult = Calculator.Add(2);
            additionResult = Calculator.Add(2, 3);

            int multiplicationResult = Calculator.Multiply(2);
            multiplicationResult = Calculator.Multiply(2, 4);

            Console.ReadLine();
        }
    }
}

See, we are just using the two methods inside the Calculator class but with different values for the parameters.


Sometimes we pass values to the optional parameters and sometimes we just leave them as defaults.


Now, let’s build the whole solution and browse the \OptionalParameters\bin\Debug directory.


 


 

You would notice that the ThirdPartyLibrary.dll copied there is the latest one. You can make sure of that by examining the Date Modified column as in the image below.


Method Optional Parameters Issue Problem .NET C# DotNet CSharp Code Coding Programming Software Design Development Engineering Architecture Best Practice Ahmed Tarek

Now, let’s run the application by double-clicking on the OptionalParameters.exe file. We would get the following result:


Method Optional Parameters Issue Problem .NET C# DotNet CSharp Code Coding Programming Software Design Development Engineering Architecture Best Practice Ahmed Tarek
Result. Image by Ahmed Tarek

As expected, right?


Now, let’s do a minor change to the Calculator class. We would change the default values of the optional parameters to 10 instead of 0.


So, the code would be as follows:


using System;

namespace ThirdPartyLibrary
{
    public static class Calculator
    {
        public static int Add(int a = 0, int b = 10)
        {
            Console.WriteLine($"Add => a: {a}, b: {b}");
            return a + b;
        }

        public static int Multiply(int a, int b = 10)
        {
            Console.WriteLine($"Multiply => a: {a}, b: {b}");
            return a * b;
        }
    }
}

Now, from VS, right-click on the ThirdPartyLibrary project and click Build.


When you browse to the \OptionalParameters\bin\Debug directory, you would notice that the ThirdPartyLibrary.dll copied there is not the latest one. You can make sure of that by examining the Date Modified column.


To fix this, let’s browse the \ThirdPartyLibrary\bin\Debug directory and copy the ThirdPartyLibrary.dll and ThirdPartyLibrary.pdb files to the \OptionalParameters\bin\Debug directory. Now, it is the latest one.


Method Optional Parameters Issue Problem .NET C# DotNet CSharp Code Coding Programming Software Design Development Engineering Architecture Best Practice Ahmed Tarek

Now, let’s run the application by double-clicking on the OptionalParameters.exe file. We would get the following result:


Method Optional Parameters Issue Problem .NET C# DotNet CSharp Code Coding Programming Software Design Development Engineering Architecture Best Practice Ahmed Tarek
Result. Image by Ahmed Tarek

I can hear you now screaming:

What the hell?!!!! How come the default values are still 0 when we already changed them to 10? Didn’t we build the ThirdPartyLibrary project?!!! Didn’t we copy the latest DLL files?!!!

Yes, we did build the ThirdPartyLibrary project and we did copy the latest DLL files. However, this is not enough. Let me explain it to you.


Before explaining what actually happened, let’s quickly try something.


Let’s build the whole solution and run our OptionalParameters project but not from VS itself. Let’s do it by browsing to the \OptionalParameters\bin\Debug directory and double-clicking on the OptionalParameters.exe file.


Doing so, we would get the following result:


Method Optional Parameters Issue Problem .NET C# DotNet CSharp Code Coding Programming Software Design Development Engineering Architecture Best Practice Ahmed Tarek
Result. Image by Ahmed Tarek

See, this is the result we were actually expecting the last time.

However, why didn’t it work the last time and now it works?

Let me tell you…


 


 

Method Optional Parameters Issue Problem .NET C# DotNet CSharp Code Coding Programming Software Design Development Engineering Architecture Best Practice Ahmed Tarek
The Catch. Photo by Alex Sheldon on Unsplash, adjusted by Ahmed Tarek

The Catch


When you call a method with optional parameters and you don’t pass values for some or all of these optional parameters, the default values defined by the method would be used.


But, this is not all. These default values would be integrated into the caller-side compiled code. This means that when the default values are updated into the method definition, this would not reflect in the caller till both projects are re-built, building only one of them is not enough.


Having said that, you need to be so careful while using optional parameters. If there is a possibility that the method provider project could be updated and built without re-building the method caller project, this is a risk.


 

Method Optional Parameters Issue Problem .NET C# DotNet CSharp Code Coding Programming Software Design Development Engineering Architecture Best Practice Ahmed Tarek
Final Thoughts. Photo by Kenny Eliason on Unsplash, adjusted by Ahmed Tarek

Final Thoughts


In this article, I explained the dangers of using Optional Parameters which you need to keep in mind.


You might ask:

But how to avoid such thing? Sometimes I really need to use Optional Parameters?

My answer would be:

  • Try to use method overloads if possible.

  • You can try to use a default settings class instead of depending on optional parameters.


Finally, I hope you enjoyed reading this article as I enjoyed writing it.



Recent Posts

See All

Subscribe to get best practices, tutorials, and many other cool things directly to your email inbox

bottom of page
Mastodon Mastodon