[Use of C # Foundation]ref and out

Source: Internet
Author: User

In C # If you need to convert a value type to a reference type and pass other methods and make its original value change, use ref and out to convert to a reference type pass.

1. Ref: A variable needs to be defined and initialized before using ref (must be initialized)

Class program    {        static void Main (string[] args)        {                        int i = 10;//define variable and initialize;            Console.WriteLine ("i =" + i);  Print Demo before delivery            (ref i);  By ref I change the reference pass            Console.WriteLine ("i =" + i);                       Console.readkey ();        }        The Receive method parameter also uses the REF keyword public        static void Demo (ref int i)        {            i = i + +;        }          }

Printing results:

2. Out: You need to define variables before using out, do not initialize; Initialization is left to the called method.

Class program    {        static void Main (string[] args)        {                        int i;//define variable [without initialization], if initialized here, the receiving method will be replaced;                 Demo (out i);  By passing out I change the reference pass            Console.WriteLine ("i =" + i);                       Console.readkey ();        }        The Receive method parameter also uses        the OUT keyword public static void Demo (out int i)        {            i = 100;//using the Out method initial work is done inside the methods            i = i + 200;< c14/>//I  + max = +}          }

The printing results are as follows:

[Use of C # Foundation]ref and out

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.