Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Have a "Optional" Parameter that by default uses the value of a required parameter

Tags:

c#

nullable

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?

like image 649
Jiew Meng Avatar asked Aug 27 '10 07:08

Jiew Meng


2 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 the string?. System.String is a reference type and can already be null. The Nullable<T> structure can only be used on value types.

like image 78
Steven Avatar answered Sep 30 '22 01:09

Steven


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);
} 
like image 41
cjk Avatar answered Sep 29 '22 23:09

cjk