Thursday, April 23, 2009

Pass by reference to a Web Service

Few days back someone asked me if we can pass value by reference to a web method. I thought why would some one want to pass parameter's reference to a web method because parameter's reference will point to memory location in client machine whereas web method will be invoked on the server machine where that reference will be invalid.
Anyways, the reality is that you can pass value by reference to a web method if it allows so. In fact you can also create web method that will take "out" parameter.

In Web Methods parameters can be passed by reference using “ref” keywords just like any other method.
Like –
[WebMethod]
public void WebMethod2(ref int iparam)
{
iparam = iparam + 100;
}

And in the proxy class at the client end it is declared as below:

public void WebMethod2(ref int iparam)
{
object[] results = this.Invoke("WebMethod2", new object[] {iparam});
iparam = ((int)(results[0]));
}


Web Methods can also have “out” parameters.
Like -
[WebMethod]
public string WebMethod1(string str,out int iReturn)
{
string temp = "Hello " + str;
iReturn = temp.Length;
return temp;
}

And in the proxy class at the client end it is declared as below:

public string WebMethod1(string str, out int iReturn)
{
object[] results = this.Invoke("WebMethod1", new object[] {str});
iReturn = ((int)(results[1]));
return ((string)(results[0]));
}

No comments: