Four types of method parameters in C #

Source: Internet
Author: User
Tags modifier

There are four types of parameters for methods in C #:

-Value parameter: does not contain any modifiers. The formal parameter in the method is a copy of the argument, and the change of the formal parameter does not affect the value of the actual parameter in memory, and the argument is safe.

-Reference parameters: declared with a ref modifier. The parameter passed is actually a pointer to the argument, so the operations in the method are all directly to the arguments, rather than copying a value, which can be used in both directions when the method calls, and in order to use the arguments in ref, you must explicitly specify the REF keyword in both the method declaration and the method call. And real parametric must be initialized before they are passed to the method.

-Output parameter: declared as an out modifier. Similar to ref, it also operates directly on an argument. The Out keyword must be specified explicitly in both the method declaration and the method invocation. The out parameter declaration method does not require a variable to be initialized before it is passed to the method, because its meaning is used only for output purposes. However, the out parameter must be assigned before the method returns.

-array parameter: declared with params modifier. The params keyword is used to declare a variable-length argument list. A method declaration can contain only one params parameter.

using System;
class Test
{
    static void F(params int[] args)
    {
       Console.WriteLine("Array contains {0} elements:",args.Length);
       foreach(int i in args)
           Console.Write("{0}",i);
       Console.WriteLine();
    }
    public static void Main()
    {
       int [] a = {1,2,3};
       F(a);
       F(10,20,30,40);
       F();
}
}

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.