Out parameter, ref parameter, params parameter array

Source: Internet
Author: User

Params parameter array

The params keyword can specify a variable number of parameters for a method. Parameters modified by the params keyword can pass in any number of the same type parameters, even without passing in parameters.

However, the params -Modified parameter must be the last parameter of the method, and a method can have only one params-decorated parameter.

Example
 Public classmyclass{ Public Static voidUseparams (params int[] list) {         for(inti =0; I < list. Length; i++) {Console.Write (List[i]+" ");    } Console.WriteLine (); }     Public Static voidUSEPARAMS2 (params Object[] list) {         for(inti =0; I < list. Length; i++) {Console.Write (List[i]+" ");    } Console.WriteLine (); }    Static voidMain () {//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 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 to an integer array. //Useparams (Myobjarray); //The following call does not cause a error, but the entire//The 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 arguments.

Ref reference parameter

The ref keyword makes a parameter pass through a reference (not a value pass). The effect of passing parameters by reference is that any changes to the parameters in the method are preserved.

Description : Reference passing and reference types are two concepts, do not confuse. Value types and reference types can be decorated with ref , and value types are not boxed when passed by reference.

To use the ref parameter, both the definition and invocation of the method must explicitly use the ref keyword, as follows:

classRefexample {Static voidMethod (ref inti) {//Rest The mouse pointer over I-Verify that it's an int. //The following statement would cause a compiler error if I//were boxed as an object.i = i + -; }        Static voidMain () {intval =1; Method (refval);            Console.WriteLine (Val); //output:45        }    }

An argument passed to a ref parameter must be initialized before it can be used. This is different from out parameters, which can be uninitialized before an out parameter is used.

Method signatures in the same class, the difference cannot be only that the parameter decorations are ref and out respectively. If the difference between the two methods is only that one is a ref parameter and the other is an out parameter, a compilation error occurs. For example, the following code compiles an error:

class cs0663_example{    //  Compiler error CS0663: "Cannot define overloaded     // Methods that differ only on ref and out ".     Public void SampleMethod (outint  i) {}    publicvoid SampleMethod ( ref int i) {}}

However, there are ref (out) and no ref (out) functions that can be overloaded, as shown below, by compiling:

class refoverloadexample{        publicvoid samplemethod (int  i) {}          publicvoid SampleMethod (refint  i) {}}

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

The following types of methods cannot use the ref and out keywords:

    • An async method, that is, a method that is decorated with the async modifier.
    • The iterator method, including the yield return or yield break declaration statement.
Out output parameters

The out has been introduced in ref and the out parameter is parsed in detail below. The Out keyword can be applied in two places: a parameter modifier; an interface or a delegate that modifies a generic type parameter. The parameter modifiers section is introduced first.

Parameter decoration

The

out keyword passes parameters by reference. This is similar to the REF keyword, but ref requires that a variable be initialized before it is passed, and out does not have this requirement. As with ref, the out keyword must be explicitly used at both the method definition and the call. For example:

class outexample{    staticvoid Method (outint  i)    {          - ;    }     Static void Main ()    {        int  value;        Method (out  value);         // value is now     }}

Although a variable passed by an out parameter does not have to be initialized before it is passed, it needs to be assigned before the method returns.

Example

If you want the method to return more than one value, 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 is assigned a null value, which allows the method to return the value by selection.

classOutreturnexample {Static voidMethod ( out intI out stringS1, out stringS2) {i= -; S1="I ' ve been returned"; S2=NULL; }        Static voidMain () {intvalue; stringstr1, str2; Method ( outValue outSTR1, outstr2); //value is now//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 parameter is covariant. You can use the Out keyword in generic interfaces and delegates.

With covariance, you can use a type that is more derived than the specified type. This allows you to implicitly convert the delegate type and the class that implements the Variant interface. Reference types support covariance and contravariance, and value types are not supported.

If the interface has covariant type parameters, it is allowed to return more derived arguments. For example, the Ienumerable<t> interface in the. NET framework 4, whose type T is covariant, eliminates the need to use any special conversion method to ienumerable<of the string> An object of type Ienumerable<of is assigned to an object of type object>.

You can assign other delegates of the same type to the covariant delegate, but you need to use a larger generic type parameter from the derived program.

Example

The following shows how to declare, extend, and implement a covariant generic interface. It also shows how to use implicit conversions for classes that implement covariant interfaces.

//covariant interface.Interfaceicovariant< outR> { }//extending covariant interface.Interfaceiextcovariant< outR>: icovariant<r> { }//implementing covariant interface.classSample<r>: icovariant<r> { }classprogram{Static voidTest () {icovariant<Object> iobj =NewSample<object>(); Icovariant<String> ISTR =NewSample<string>(); //You can assign ISTR to Iobj because//The Icovariant interface is covariant.Iobj =ISTR; }}

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

    • A type parameter is used only as the return type of an interface method, not as a type of a method argument.
      Description: This rule has an exception where covariant types can be used as parameters for this delegate type if you include an contravariant generic delegate that is used as a method parameter in the covariant interface.
    • Type parameters are not used as generic constraints for interface methods.

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

//covariant delegate. Public DelegateR dcovariant< outR>();//Methods that match the delegate signature. Public StaticControl Samplecontrol () {return NewControl ();} Public StaticButton SampleButton () {return NewButton ();} Public voidTest () {//instantiate the delegates with the methods.Dcovariant<control> Dcontrol =Samplecontrol; Dcovariant<Button> Dbutton =SampleButton; //can assign Dbutton to Dcontrol//because the Dcovariant delegate is covariant.Dcontrol =Dbutton; //Invoke the delegate.Dcontrol ();}

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

Out parameter, ref parameter, params parameter array

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.