C # ref out difference comparison rollup __c#

Source: Internet
Author: User
Tags modifier
ref (C # Reference) Visual Studio 2015Other versions

The REF keyword causes the parameter to be passed by reference, not by value. The effect passed by reference is that any changes to the parameters in the called method are reflected in the calling method. For example, if the caller passes a local variable expression or an array element access expression, the calling method replaces the object with the object referenced by the ref parameter, and then the local variable or array element of the caller begins referencing the new object.

Attention

Do not confuse the notion of passing by reference with the concept of a reference type. The two concepts are different. The method parameter, whether it is a value type or a reference type, can be modified by ref . When passed by reference, the value type is not boxed.

To use the ref parameter, both the method definition and the calling method must explicitly use the ref keyword, as shown in the following example. C #

Class Refexample
{
    static void method (ref int i)
    {
        //Rest the mouse pointer over I to verify ' it is a n Int.
        The following statement would cause a compiler error if I
        //were boxed as an object.
        i = i +;

    static void Main ()
    {
        int val = 1;
        Method (ref val);
        Console.WriteLine (val);

        Output:45
    }
}

The arguments passed to the ref parameter must be initialized before they can be passed. This is different from an out parameter, and you do not need to explicitly initialize the argument of the formal parameter before passing it. For more information, see out.

A member of a class cannot have a signature that differs only in ref and out. If the only difference between the two members of a type is that one has a ref parameter and the other has an out parameter, a compilation error occurs. For example, the following code will not compile. C #

Class Cs0663_example
{
    //Compiler error CS0663: "Cannot define overloaded 
    //methods that differ in ref And out ".
    public void SampleMethod (out int i) {} public
    void SampleMethod (ref int i) {}
}

However, when a method has a ref or out parameter and another method has a value parameter, the overload can be completed, as shown in the following example. C #

Class Refoverloadexample
{public
    void SampleMethod (int i) {} public
    void SampleMethod (ref int i) {}
   
    } 
   

In other cases where signature matching is required (such as shadowing or overriding),ref and out are part of the signature and do not match each other.

property is not a variable. They are methods and cannot be passed to ref parameters.

For information about how to pass an array, see Using the ref and out pass arrays (C # Programming Guide).

You cannot use ref and out keywords in the following ways:

asynchronous method, defined by using the async modifier.

Iterator methods, including yield return or yield break statements. Sample

The preceding example of

shows what happens when a value type is passed by reference. You can also use the ref keyword to pass a reference type. Passing a reference type by reference enables the calling method to replace the object in the calling method with the object referenced by the reference parameter. The storage location of the object is passed to the method by the value of the reference parameter. If you change the value in the parameter store location (to point to the new object), you can also modify the storage location to the location referenced by the caller. The following example passes an instance of a reference type as a ref parameter. For more information about how to pass reference types by value and reference, see passing reference type parameters (C # Programming Guide). C #

Class RefExample2 {static void Changebyreference (ref Product Itemref) {//The following line changes the Address this is stored in//parameter itemref.
        Because Itemref is a ref parameter and the/address this is stored in variable item in Main also is changed.

        Itemref = new Product ("stapler", 99999); Can change the value of one of the properties of//Itemref.
        The change is happens to item in Main as.
    Itemref.itemid = 12345;
        The static void Main () {//Declare an instance of Product and display its initial values.
        Product item = new Product ("fasteners", 54321);  System.Console.WriteLine ("Original values in Main.") Name: {0}, ID: {1}\n, item. ItemName, item.

        ItemID);
        Send item to Changebyreference as a ref argument.
        Changebyreference (ref item);  System.Console.WriteLine ("Back in Main".) Name: {0}, ID: {1}\n, item. ItemName, item.ItemID);
        Class Product {public product (string name, int newID) {itemname = name;
    ItemID = NewID;
    public string ItemName {get; set;}

public int ItemID {get; set;}}  Output://original values in Main.  Name:fasteners, id:54321//back in Main.

 Name:stapler, id:12345
Out (C # Reference)

You can use the out context keyword as a parameter modifier in two contexts (each link that points to details), or use a generic type parameter declaration in interfaces and delegates. This topic discusses parameter modifiers, but you can see other topics for information about generic type parameter declarations.

The Out keyword passes parameters by reference. This is similar to the REF keyword, except that ref requires that the variable be initialized before it is passed. To use an out parameter, both method definitions and calling methods must explicitly use the Out keyword. For example: C #

Class Outexample
{
    static void method (out int i)
    {
        i =;
    }
    static void Main ()
    {
        int value;
        Method (out value);
        Value is now}
}

Although a variable passed as an out parameter does not need to be initialized before it is passed, the calling method still requires a value to be assigned before the method returns.

Although the ref and Out keywords cause different run-time behavior, they are not considered part of the compile-time method signature. Therefore, if the only difference is that a method takes a ref parameter and another method takes an out parameter, the two methods cannot be overloaded. For example, the following code will not compile: C #

Class Cs0663_example
{
    //Compiler error CS0663: "Cannot define overloaded 
    //methods that differ in ref And out ".
    public void SampleMethod (out int i) {} public
    void SampleMethod (ref int i) {}
}

However, if a method takes a ref or out parameter, and another method takes another parameter, the overload can be completed, such as: C #

Class Outoverloadexample
{public
    void SampleMethod (int i) {} public
    void SampleMethod (out int i) {i = 5; }
}

property is not a variable and cannot be passed as an out parameter.

For information about passing arrays, see Using the ref and out pass arrays (C # Programming Guide).

You cannot use ref and out keywords in the following ways:

asynchronous method, defined by using the async modifier.

Iterator methods, including yield return or yield break statements.

If you want the method to return multiple values , you can declare the Out method. The following example uses out to return three variables with a single method call. Note that the third parameter assigns a null value. This allows the method to optionally return a value. C #

Class Outreturnexample
{
    static void method (out int. I, out string s1, out string s2)
    {
        i =;
        S1 = "I ' ve been returned";
        s2 = null;
    }
    static void Main ()
    {
        int value;
        String str1, str2;
        Method (out value, out str1, out str2);
        Value is now
        //str1 are now "I ' ve been returned"
        //STR2 is (still) null;
    }
See:
https://msdn.microsoft.com/zh-cn/library/t3c3bfhx.aspx
https://msdn.microsoft.com/zh-cn/library/ 14akc2c7.aspx

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.