Usage and difference of out and ref in C #

Source: Internet
Author: User

1. The out must be initialized in the function body. It does not make sense to initialize it outside.That is to say, an out-type parameter cannot obtain the initial value passed in outside the function body.
2. Ref must be initialized in vitro.
3. Any modification to both of them in the function body will affect the outside.

Example:

Using system;

Namespace consoleapplication1
{
Class C
{
Public static void reffun (ref string Str)
{
STR + = "fun ";
}

Public static void outfun (out string Str)
{
STR = "test"; // It must be initialized in the function body
STR + = "fun ";
}
}

Class class1
{
[Stathread]
Static void main (string [] ARGs)
{
String test1 = "test ";
String Test2; // No Initialization
C. reffun (ref test1); // correct
C. reffun (ref Test2); // error. Test2 is used if no value is assigned.
C. outfun (Out test1); // correct, but the value test is passed in.
C. outfun (Out Test2); // correct

Console. Read ();
}
}
}

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.