How can i implement a "optional" parameter to a function such that when endMarker
is not given, i will use the value from a required parameter startMarker
? i currently use a nullable type and check if endMarker
is null i set it to startMarker
protected void wrapText(string startMarker, string? endMarker = null) {
if (endMarker == null)
endMarker = startMarker;
}
but the problem now is i get an error saying it cannot cast string?
into string
(string)endMarker
how can i cast endMarker
to a string
so i can use it? or is there a better way of implementing this?
This will work:
protected void wrapText(string startMarker, string endMarker = null) {
if (endMarker == null)
endMarker = startMarker;
}
In other words: remove the question mark from the string?
. System.String
is a reference type and can already be null
. The Nullable<T>
structure can only be used on value types.
You need to overload the method to have a call without the "optional" parameter. Then in this method you just call the normal method passing in the same parameter twice:
protected void wrapText(String startMarker, String endMarker)
{
// do stuff
}
protected void wrapText(String startMarker)
{
wrapText(startMarker, startMarker);
}
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