The Out, params, and ref in c # are detailed and precipitated.

Source: Internet
Author: User

1. Before "Out", "params" and "ref", the most commonly used parameter passing by value is recorded. Of course, by default, the default behavior of parameter passing in to the function is also passed by value.

1: // by default, parameters are passed by value
   2:          static int add(int x,int y) {
   3:              int ans = x + y;
   4:              x = 1000; y = 2000;
   5:              return ans;
   6:          }
 
   1:     static void Main(string[] args) {
2: Console. WriteLine ("pass by value by default ");
   3:              int x = 3, y = 8;
4: Console. WriteLine ("before calling: x: {0}, y: {1}", x, y );
5: Console. WriteLine ("result after call: {0}", add (x, y ));
6: Console. WriteLine ("after calling: x: {0}, y: {1}", x, y );
   7:              Console.ReadLine();
   8:          }

The output result is as expected:

2. Out Modifier

   1:    static void add(int x,int y,out int ans) {
   2:              ans = x + y;
   3:          }

 

This can be written in Main:

   1:   int ans;
   2:   add(20, 20, out ans);
   3:   Console.WriteLine("20+20={0}", ans);
   4:   Console.ReadLine();

Of course, the output result is: 20 + 20 = 40. In the past, if no out is used, "the unassigned local variable is used ".

Even if we assign a value to ans, for example, int ans = 10;

It does not change after calling the add method, because the called method does not know what is going on.

This turns to 20 + 20 = 10, which is obviously wrong.

Of course, the biggest highlight of Out is that multiple parameter values can be output after a function call.

Change the above method:

   1:     static void setParams(out int x,out string y,out bool ans) {
   2:              x = 2;
   3:              y = "YeanJay";
   4:              ans = true;
   5:          }

We can write this in Main:

Related Article

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.