The difference between out and ref in C #

Source: Internet
Author: User

First: Both are passed by address and will change the value of the original parameter after use.

Second: Rel can pass the value of the parameter into the function, but out is to empty the parameters, that is, you can not transfer a value from out into the, out into the parameter value is empty, so you have to initialize it once. This is the two difference, or as some netizens said, Rel is in there, out is only out.

ref(C # Reference)refKeyword causes parameters to be passed by reference. The effect is that when control is passed back to the calling method, any changes to the parameters in the method are reflected in the variable. To userefparameter, both the method definition and the calling method must be explicitly usedrefkey word. For example:classrefexample{Static voidMethod (ref inti) {i= -; }    Static voidMain () {intval =0; Method (refval); //Val is now}} is passed torefThe parameters of the parameter must be initialized first. This with out, the latter's parameters do not need to be explicitly initialized before being passed.

 out(C # Reference) outKeywords cause parameters to be passed by reference. This withrefKeyword is similar, the difference is thatrefRequires that the variable be initialized before it is passed. To use outParameters, method definitions, and calling methods must be explicitly used outkey word. For example:classoutexample{Static voidMethod ( out inti) {i= -; }    Static voidMain () {intvalue; Method ( outvalue); //value is now}} Although as outA variable passed by a parameter does not have to be initialized before it is passed, but the method needs to be called to assign a value before the method returns. 

The difference between out and ref in C #

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.