Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a null-value color

Tags:

c#

null

I just wonder how I can pass a null colour to a method.

Here is an example with a method which gets a color parameter:

protected void myMethod(Color color,other parameters...) {}

Now I am using the shown condition. Depending on that condition I would like to change the color.

if(1) {myMethod(Color.Red,....)}

if(2) {myMethod(Color.Black,...)}

if(3) {myMethod(Color.Ignore,...)} //so here just ignore this color parameter and keep the original.

I know I can do many things to overcome this but as I said I just wonder is there any better way of passing an ignore value, so it will use the original color of the element.

like image 240
akd Avatar asked Nov 29 '22 00:11

akd


2 Answers

What about:

protected void myMethod(Color? color,other parameters...) {}

Where Colour? is nullable, so you can pass null instead and check for the value in your method. If colour == null then keep the original?

like image 74
David A Gibson Avatar answered Dec 05 '22 12:12

David A Gibson


Create an overload of method which will not require color and call it if you want to use default value (it's better not to provide argument at all, if you are not going to use it in the method than passing null value to the method):

protected void myMethod(other parameters...)

Also I suggest you to put optional parameter to the end of parameters:

protected void myMethod(other parameters..,  Color color)

Code:

switch(value)
{
   case 1: myMethod(..., Color.Red); break;
   case 2: myMethod(..., Color.Black); break;
   case 3: myMethod(...); break;
}

You can even ask compiler to make 'overload' (see comments) for you:

protected void myMethod(other parameters..,  Color color = {DefaultColor})

NOTE: I like to avoid any confusing code. E.g. call

DrawPoint(10, 20, null)

looks very confusing to me. What is null? Why you are passing null if nobody will be able to use it in the method? Following call looks better

DrawPoint(10, 20) 

It does not mess caller with passing parameters which will not be used. I don't need to think what null means. But even in this case we know some information which is still not available for other developers - we are drawing point with default color, and method does not tell anything about it. So, I'd use another method

DrawPointWithDefaultColor(10, 20)

Completely not confusing.

like image 31
Sergey Berezovskiy Avatar answered Dec 05 '22 13:12

Sergey Berezovskiy