Rajkiran Swain
In how many ways you can pass parameters to a method in c# ?
By Rajkiran Swain in SharePoint on May 10 2017
  • Piyush Agarwal
    Mar, 2018 7

    Pass by Value and Pass by reference. In pass by reference the original value gets changed if the value is changed in the calling function however the value is not changed in pass by value .

    • 1
  • Rajkiran Swain
    May, 2017 10

    We can categorize method parameters in various parts. Some of them are: Named Parameters (C# 4.0 and above) Ref Parameter (Passing Value Types by Reference) Out Parameters Default Parameters or Optional Arguments (C# 4.0 and above) Dynamic parameter (dynamic keyword). Value parameter or Passing Value Types by Value (normal C# method param are value parameter) Params (params)

    • 1
  • Praween Kumar
    Oct, 2019 27

    In C#, arguments can be passed to parameters either by value or by reference. Passing by reference enables function members, methods, properties, indexers, operators, and constructors to change the value of the parameters and have that change persist in the calling environment. To pass a parameter by reference with the intent of changing the value, use the ref, or out keyword. To pass by reference with the intent of avoiding copying but not changing the value, use the in modifier. For simplicity, only the ref keyword is used in the examples in this topic. For more information about the difference between in, ref, and out, see in, ref, and out.

    The following example illustrates the difference between value and reference parameters.

    C#

    Copy
    class Program
    {
    static void Main(string[] args)
    {
    int arg;

    1. // Passing by value.
    2. // The value of arg in Main is not changed.
    3. arg = 4;
    4. squareVal(arg);
    5. Console.WriteLine(arg);
    6. // Output: 4
    7. // Passing by reference.
    8. // The value of arg in Main is changed.
    9. arg = 4;
    10. squareRef(ref arg);
    11. Console.WriteLine(arg);
    12. // Output: 16
    13. }
    14. static void squareVal(int valParameter)
    15. {
    16. valParameter *= valParameter;
    17. }
    18. // Passing by reference
    19. static void squareRef(ref int refParameter)
    20. {
    21. refParameter *= refParameter;
    22. }

    }

    • 0

Most Popular Job Functions

MOST LIKED QUESTIONS