After using [Optional] Parameter in c# how to know if It was given by the calling method or not?

Viewed 597

I want to know if parameter b was provided by the calling method or not so that I can condition it within the definition of method according to it. As there is always a default value of "b" here 0 but I want to distinguish between user calling cc(5,0) and cc(5).

Is there any way to know it?

     class Program
        {
            static void Main(string[] args)
            {
               var c= cc(5);
            }
            public static int cc(int a, [Optional] int b)
            {
              int c=0;
            //if(b is provided)
              c = a * b;
            //else()
              c =a*a;    
              return c;
            }
        }
2 Answers

You cannot, via that mechanism. Even if you used int? b = null, the caller could have explicitly specified null. To know, you'd have to use overloads instead of optional parameters, for example:

public static int cc(int a) => cc(a, 0, false);
public static int cc(int a, int b) => cc(a, b, true);
private static int cc(int a, int b, bool bSpecified) // could also use int? here
{...}

When you write a method with optional arguments. The compiler will insert the default argument values at the call site.

public static int cc(int a, int b = 0){...}
// these are exactly the same at runtime;
cc(5);
cc(5,0);

While you could use a different magic value int b = Int32.MinValue, or int? b = default. Since you want different behaviour anyway, why not just write two methods;

public static int cc(int a, int b) => a*b;
public static int cc(int a) => a*a;
// these are now calling different methods;
cc(5);
cc(5,0);
Related