Thursday, October 13, 2011

Difference between ref and out parameters in c#

The difference between ref and out parameters is at the language level. In case of ref you must have to assign it as in "Example by ref" string val is assigned.
In case of out you don't need to assign an out parameter before passing it to a method. But the out parameter in that method must assign the parameter before returning.

Example

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        
        Response.Write("Example by ref");
        string val = "hello";
        ExampleByRef(ref  val);
        Response.Write(val);
        Response.Write("Example by out
"); string vals; ExampleByOut(out vals); } public static void ExampleByRef(ref string val) { if (val == "hello") { System.Web.HttpContext.Current.Response.Write("Example by ref case"); } else { System.Web.HttpContext.Current.Response.Write("Example by ref else response"); } val = "hi"; } public static void ExampleByOut(out string vals) { vals = "Example by Out case
"; System.Web.HttpContext.Current.Response.Write(vals); } }


Output
Example by ref
Example by ref case
hi
Example by out
Example by Out case