Output parameter out and reference parameter ref difference

Source: Internet
Author: User

A section of code using ref

using System;
class M
{
public void F(ref int i)
{
i=3;
}
}
class Test
{
int i=0; //要作为引用参数传递的变量必须明确赋值
static void Main()
{ //不能把int i=0;放在这里赋值,会报错说Test不包含i定义。
Test t=new Test();
Console.WriteLine("the value of i is:{0}",t.i);
M mm=new M();
mm.F(ref t.i); //作为引用参数传递
Console.WriteLine("now the value of i is :{0}",t.i); //i的值改变
}
}

Use out a piece of code like this

class M
    {
        public void F(out int i) //这个方法和ref的方法都是一样,没什么不同
        {
            i = 8; //返回前必须明确赋值
        }
    }
    class Test
    {
        int i; //不用赋初值,这就是out和ref的区别,但声明还是要的
        public static void Main()
        {
            Test t1 = new Test();
            Console.WriteLine("the value of i is :{0}", t1.i); //输出是0;
            M m1 = new M();
            m1.F(out t1.i); //i作为输出参数传递 ,输出是8
            Console.WriteLine("now value of i is :{0}", t1.i);
        }
    }

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.