parameters var - optional/null-able OUT parameter in C#




assign to (5)

Yes, Nullable variables are great. You would then do something like this.

public bool? IsPossible(string param1, int param2);

var ans = IsPossible("Parm1", 1);
if (ans.HasValue)
{
   //working.
 }

I have a method that has several overrides. In one of the more expanded overrides, I want to return an OUT parameter but not in my simpler overrides. For example:

public bool IsPossible(string param1, int param2)
public bool IsPossible(string param1, int param2, out bool param3)

The way I am currently achieving this, is like so:

public bool IsPossible(string param1, int param2) {
    bool temp;
    return IsPossible(param1, param2, out temp);
}

Is there a better way to achieve this? Can I (or should I) use a null-able out parameter?


A 'ref' or 'out' parameter cannot have a default value.

The way you've done it is just fine. Sorry, no silver bullet.


That looks fine to me. A out cannot be optional for technical reasons (it needs to point to a valid instance).


Personally I think it is fine "as is". Another approach, though, is to return a composite return value (perhaps an immutable struct with 2 properties); that avoids the fact that some people avoid out. I am not one of those people :p

Re the question; indeed, out/ref can't be optional.

If you wanted to get unnecessarily fancy you could give the conposite return-type a conversion to bool to allow implicit if tests.


Some of the webservices require you to place request data and metadata separately. For example a remote function may expect that the signed metadata string is included in a URI, while the data is posted in a HTTP-body.

The POST request may semantically look like this:

POST /?AuthId=YOURKEY&Action=WebServiceAction&Signature=rcLXfkPldrYm04 HTTP/1.1
Content-Type: text/tab-separated-values; charset=iso-8859-1
Content-Length: []
Host: webservices.domain.com
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: identity
User-Agent: Mozilla/3.0 (compatible; Indy Library)

name    id
John    G12N
Sarah   J87M
Bob     N33Y

This approach logically combines QueryString and Body-Post using a single Content-Type which is a "parsing-instruction" for a web-server.

Please note: HTTP/1.1 is wrapped with the #32 (space) on the left and with #10 (Line feed) on the right.





c# parameters nullable