Search code examples
c#nullableoptional-parameters

Check if optional byte argument was passed in


I want to let a user specify a custom color for a class in the constructor via passing in RGBA bytes. If they do not specify a custom color, a default color from the application settings will be used. If the Alpha is left out, however, assume fully opaque.

What I would like:

public MyClass(byte r_col = -1, byte g_col = -1, byte b_col = -1, byte a_col = 255)
{
    if (r_col == -1 | g_col == -1 | b_col == -1)
    {
        // use default color
    }
    else
    {
        this.color = System.Windows.Media.Color.FromArgb(a_col, r_col, g_col, b_col); 
    }
}

However, there is no "wrong" value for a byte (-1 is invalid), so I am unable to detect if a byte was actually passed into the function. What options do I have? I'd like to avoid function overloading if possible.


Solution

  • Function overloading is much more beautiful in this case:

    public MyClass()
    {
        //Default color
    }
    public MyClass(byte r_col, byte g_col, byte b_col)
    {
        color = Color.FromArgb(r_col, g_col, b_col);
    }
    public MyClass(byte a_col, byte r_col, byte g_col, byte b_col)
    {
        color = Color.FromArgb(a_col, r_col, g_col, b_col);
    }
    

    Of course it is possible to do it without (as Micheal proofed), but it's (P.Kouverakis mentioned) not good API design. Because if you let the user type in parameters, which aren't allowed, this may result in difficult to trace bugs. Never fear more work for a greater result - so in this case, use function overloads.