Consider a method like this:
public void WorkAt(string location = @"home") { //... }
It can be called by passing a value explicitly, like:
WorkAt(@"company"); WorkAt(@"home");
Or just use the default value, like:
WorkAt();
Is there a way to know whether the default value is used?
For example, I want to code like this:
public void WorkAt(string location = @"home") { if ( /* the default value is used unexplicitly */) { // Do something } else { // Do another thing } }
Be careful that WorkAt("home")
is different from WorkAt()
in this context.
Right-click the control that you want to change, and then click Properties or press F4. Click the All tab in the property sheet, locate the Default Value property, and then enter your default value.
A default value can be applied to a column when it is created with the default keyword. If an explicit value is not provided for that column when data is inserted, the specified default value is used.
A DEFAULT value clause in a data type specification explicitly indicates a default value for a column. Examples: CREATE TABLE t1 ( i INT DEFAULT -1, c VARCHAR(10) DEFAULT '', price DOUBLE(16,2) DEFAULT 0.00 ); SERIAL DEFAULT VALUE is a special case.
default value means a value derived from a typical value by the application of pre-determined factors and that may, in circumstances specified in this Directive, be used in place of an actual value.
There is not, and should not be, any reason to do this. The default value is there to do just that - provide a default value when none is specified.
If you need to perform a different function based on what is passed, I suggest overloading the method. For example:
public void WorkAt() { //do something } public void WorkAt(string location) { //do other thing }
Alternatively, if there is shared logic, you could use an additional parameter:
public void WorkAt(string location = "home", bool doOtherThingInstead = false) { if (!doOtherThingInstead) { //do something } else { //do other thing } //do some shared logic for location, regardless of doOtherThingInstead }
As a side note, perhaps the example in the question was contrived, but WorkAt()
with no parameter specified makes no lexical sense. One would expect a value after the word at. Perhaps you may want to rename the second method WorkAtDefaultLocation()
.
Your answer might be something like the following code.
public void CommonOperations(/*Some parameteres as needed.*/) { // Shared operations between two methods. } public void WorkAt() { string location = "home"; CommonOperations(/*Some parameteres as needed.*/); //do something } public void WorkAt(string location) { CommonOperations(/*Some parameteres as needed.*/); //do the other thing }
I hope it will help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With