JumpStart # 2 – OUT Parameter in C#

Before looking at the code, Read about – What is JumpStart?

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    /* OUT PARAMETER - 
     * 1) OUT parameter is almost in similar with REF keyword (both passes the reference, but not 
     *    actual value), but it can be used without initialization.
     * 2) OUT is useful when we expect method to return multiple values (by still returning a value).
     * 3) Even if OUT parameter is intialized, It is still considered as un-initialized in child method.
     * 4) Cannot use the OUT parameter in the Child method without initialization.
     * 5) The OUT Parameter must be initialized before the child method completion, otherwise it will
     *    throw compile time error.
     * 6) Overloading of methods are possible with OUT or REF keywords, but two method signatures cant 
     *    differ by using REF and OUT. 
     */
    protected void Page_Load(object sender, EventArgs e)
    {
        // Out Parameter need not be initialized at the time of calling.
        string name;
        string message = "Welcome!!!";

        //use out keyword
        OutParameterSample(out name, message);

        //can use the out paramert here, as it is initialized in the method
        Response.Write(name);
        
        //Now Call overloaded method
        OutParameterSample(name, message);
    }
    protected void OutParameterSample(out string name, string message)
    {
        // Before using out parameter, we got to initialize it. or else we get compile error.
        name = "Rami";
        Response.Write(name + ", " + message);
    }

    // Valid OverLoad
    protected void OutParameterSample(string name, string message)
    {
        Response.Write(name + ", " + message);
    }

    /* InValid OverLoad
    protected void OutParameterSample(ref string name, string message)
    {
        Response.Write(name + ", " + message);
    }*/
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    </div>
    </form>
</body>
</html>

You may also like...