tags:

views:

79

answers:

4

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?

A: 

Can't you just do something like

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

}

Doozer1979
-1: This just sets `endMarker` to be `startMarker` whatever happens.
ck
better now, or should i just quit while i'm behind?
Doozer1979
You've still got a completely pointless line in there...
ck
But would it work as an ugly hack? c# noob here, so go easy
Doozer1979
+5  A: 

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.

Steven
+1 that resolves the root problem.
Danny Chen
It's important to note that this is only possible in C# 4 and onwards.
Bradley Smith
just want to add, the code can be shorten to `endMarker = endMarker ?? startMarker`
jiewmeng
A: 
string str = nullableStr.Value;

string? nullableStr = new Nullable<string>(str);
Danny Chen
-1: These two declarative statements rely on each other!
ck
Danny Chen
@Danny Chen - -1 removed :-)
ck
+1  A: 

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);
} 
ck
+1 this is the solution for 3.5 and before.
Danny Chen