C #: have the parameter "Optional", which by default uses the value of the required parameter

How can I implement an “optional” parameter for a function, so when endMarker not set, will I use the value from the required startMarker parameter? I am currently using a type with a null value and checking if endMarker null, I set it to startMarker

 protected void wrapText(string startMarker, string? endMarker = null) { if (endMarker == null) endMarker = startMarker; } 

but now the problem is that I get the error message: can it not use string? in string

 (string)endMarker 

how can i use endMarker for string so i can use it? or is there a better way to implement this?

+4
source share
3 answers

This will work:

 protected void wrapText(string startMarker, string endMarker = null) { if (endMarker == null) endMarker = startMarker; } 

In other words: remove the question mark from string? . System.String is a reference type and may already be null . The Nullable<T> structure can only be used for value types.

+14
source

You need to overload the method to call without the "optional" parameter. Then, in this method, you simply call the regular method, passing through the same parameter twice:

 protected void wrapText(String startMarker, String endMarker) { // do stuff } protected void wrapText(String startMarker) { wrapText(startMarker, startMarker); } 
+2
source

Can't you do something like this:

 protected void wrapText(string startMarker, string? endMarker = null) { if (endMarker == null) { endMarker = "foo"; endMarker = startMarker; } } 
-3
source

All Articles