Out parameter, ref parameter, params parameter array, refparams

Source: Internet
Author: User

Out parameter, ref parameter, params parameter array, refparams
Params parameter Array

ParamsYou can specify a variable number of parameters for the method.ParamsYou can enter any number of parameters of the same type, or even not.

HoweverParamsThe modifier parameter must be the last parameter of the method, and a method can only have one parameter modified by params.

Example
public class MyClass{    public static void UseParams(params int[] list)    {        for (int i = 0; i < list.Length; i++)        {            Console.Write(list[i] + " ");        }        Console.WriteLine();    }    public static void UseParams2(params object[] list)    {        for (int i = 0; i < list.Length; i++)        {            Console.Write(list[i] + " ");        }        Console.WriteLine();    }    static void Main()    {        // You can send a comma-separated list of arguments of the         // specified type.        UseParams(1, 2, 3, 4);        UseParams2(1, 'a', "test");        // A params parameter accepts zero or more arguments.        // The following calling statement displays only a blank line.        UseParams2();        // An array argument can be passed, as long as the array        // type matches the parameter type of the method being called.        int[] myIntArray = { 5, 6, 7, 8, 9 };        UseParams(myIntArray);        object[] myObjArray = { 2, 'b', "test", "again" };        UseParams2(myObjArray);        // The following call causes a compiler error because the object        // array cannot be converted into an integer array.        //UseParams(myObjArray);        // The following call does not cause an error, but the entire         // integer array becomes the first element of the params array.        UseParams2(myIntArray);    }}/*Output:    1 2 3 4    1 a test    5 6 7 8 9    2 b test again    System.Int32[]*/

In this example, the UseParams method can accept any number of int type parameters, and the UseParams2 method can accept any number of object type parameters.

Ref reference parameters

RefKeyword to pass the parameter through reference (non-value transfer ). The effect of passing a parameter through reference is that any change to the parameter in the method will be retained.

Description: There are two concepts: Reference transfer and reference type. Do not confuse them. Both the value type and reference type can be used.RefWhen passed by reference, the value type is not boxed.

To useRefParameters and methods must be explicitly defined and called.RefKeyword:

class RefExample {        static void Method(ref int i) {            // Rest the mouse pointer over i to verify that it is an int.            // The following statement would cause a compiler error if i            // were boxed as an object.            i = i + 44;        }        static void Main() {            int val = 1;            Method(ref val);            Console.WriteLine(val);            // Output: 45        }    }

PassRefThe parameters must be initialized before they can be used. This correspondsOutDifferent parameters,OutYou can skip initialization before using the parameter.

The method signature in the same class. The difference is not only that the parameter modifiers are ref and out. If the difference between the two methods is that one is the ref parameter and the other is the out parameter, a compilation error occurs. For example, the following code may cause compilation errors:

class CS0663_Example{    // Compiler error CS0663: "Cannot define overloaded     // methods that differ only on ref and out".    public void SampleMethod(out int i) { }    public void SampleMethod(ref int i) { }}

However, functions with ref (out) and without ref (out) can be reloaded, as shown in the following code. You can compile the Code as follows:

class RefOverloadExample{        public void SampleMethod(int i) { }        public void SampleMethod(ref int i) { }}

Attributes are not variables, they are methods, so they cannot be passed as ref parameters.

The ref and out keywords cannot be used for the following methods:

  • Asynchronous method, that is, the method modified with the async modifier.
  • Iterator method, includingYield returnOrYield breakStatement.
Out output parameters

In ref, we have already introduced the out parameter. Next, we will parse the out parameter in detail. The out keyword can be used in two places: parameter modifier; interface or delegate to modify generic parameters. First, we will introduce the parameter modifier section.

Parameter Modification

OutThe keyword is used to pass parameters through reference. This is similar to the ref keyword,RefThe variable must be initialized before transmission,OutThis requirement is not required. Like ref, the method definition and call must be explicitly usedOutKeyword. For example:

class OutExample{    static void Method(out int i)    {        i = 44;    }    static void Main()    {        int value;        Method(out value);        // value is now 44    }}

Although the variables passed by the out parameter do not need to be initialized before being passed, they need to be assigned a value before the method is returned.

Example

If you want the method to return multiple values, you can declare the out method. The following example uses out to return three variables that have a single method call. Note that the third parameter is assigned a null value, which allows the method to return values selectively.

class OutReturnExample    {        static void Method(out int i, out string s1, out string s2)        {            i = 44;            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 44            // str1 is now "I've been returned"            // str2 is (still) null;        }    }

Generic Modifier

For generic type parameters, the out keyword can specify that the type parameters are covariant. You can use the out keyword in generic interfaces and delegation.

Through covariant, you can use a type that is greater than the specified type. In this way, you can implicitly convert the delegate type and the class that implements the variant interface. The reference type supports covariant and invert, and the value type is not supported.

If an interface has a covariant type parameter, it is allowed to return a real parameter with a greater degree of derivation. For example ,. the IEnumerable <T> interface in. NET framework 4, whose type T is covariant, therefore, you do not need to use any special conversion method to allocate IEnumerable <Of String> type objects to IEnumerable <Of Object> type objects.

Other delegates of the same type can be assigned to the covariant delegate, but larger generic type parameters of the derived program are required.

Example

The following describes how to declare, extend, and implement a covariant generic interface. It also demonstrates how to use implicit conversion for classes that implement the covariant interface.

// Covariant interface.interface ICovariant<out R> { }// Extending covariant interface.interface IExtCovariant<out R> : ICovariant<R> { }// Implementing covariant interface.class Sample<R> : ICovariant<R> { }class Program{    static void Test()    {        ICovariant<Object> iobj = new Sample<Object>();        ICovariant<String> istr = new Sample<String>();        // You can assign istr to iobj because        // the ICovariant interface is covariant.        iobj = istr;    }}

In a generic interface, when the following conditions are met, you can declare the type parameter as a covariant

  • The type parameter is only used as the return type of the interface method.
    Note: This rule has an exception. If the covariant Interface contains an inverter generic delegate used as a method parameter, the covariant type can be used as the delegate type parameter.
  • Type parameters do not need to be generic constraints of interface methods.

The following shows how to declare, instantiate, and call a covariant generic delegate:

// Covariant delegate.public delegate R DCovariant<out R>();// Methods that match the delegate signature.public static Control SampleControl(){ return new Control(); }public static Button SampleButton(){ return new Button(); }public void Test(){                // Instantiate the delegates with the methods.    DCovariant<Control> dControl = SampleControl;    DCovariant<Button> dButton = SampleButton;    // You can assign dButton to dControl    // because the DCovariant delegate is covariant.    dControl = dButton;    // Invoke the delegate.    dControl(); }

In a generic delegate, if the type is only used as the method return type and is not used as a method parameter, it can be declared as a covariant.

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.