Thursday, April 10, 2014

Out Keyword_041014

/*Notes:
The out keyword causes arguments to be passed by reference. The out keyword allows you to specify output parameters. With the use of the out keyword, a method can return more than one value (using parameters as output).
To read: http://msdn.microsoft.com/en-us/library/ee332485.aspx

//Example exercise:


namespace Methods_With_The_out_Keyword
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        //method using the out keyword
        private void ProcessData(int x, int y, out int sum, out long product)
        {
            //it is the responsibility of this method to 
            //assign a value to an out parameter, otherwise
            //you'll get a compiler error (red line under the method name)
            sum = x + y;
            product = x * y;
        }

        private void btnProcess_Click(object sender, EventArgs e)
        {
            int N1,N2;
            int S;
            long P;

            if (int.TryParse(txtInteger1.Text, out N1) && int.TryParse(txtInteger2.Text, out N2))
            {
                //call the processData method
                ProcessData(N1, N2, out S, out P);
                //N1,N2 are input parameters and therefore they
                //must have been initialized prior to calling the method.
                //S and P are output parameters,therefore they will
                //be initialize within the method.
                //Once the method completes its task, S and P will
                //contain the values assigned to Sum and Product
                //parameters of the ProcessData method
                //(out parameter P is associated with out Product
                //and out parameter S is associated with out Sum)

                rtbDisplay.Text = "Sum = " + S + "\n" +
                                 "Product = " + P;
            }
            else
                MessageBox.Show("Format Exception: Invalid data");
        }
    }
}

No comments:

Post a Comment