.NET FAQs Unleashed!
 
    
    

What are the different parameter modifiers available in C#?

What is a parameter modifier?

Parameter modifiers in C# are entities that controls the behaviour of the arguments passed in a method. Following are the different parameter modifiers in C#:
1) None - if there is NO parameter modifier with an argument, it is passed by value, where the method recieves a copy of the original data.
2) out - argument is passed by reference. The argument marked with "out" modifier needs to be assigned a value within this function, otherwise a compiler error is returned.

public void multiply(int a, int b, out int prod)
{
 prod = a * b;
}

Here, note that prod is assigned a value. If not done so, then a compile time error is returned.
3) params- This modifier gives the permission to set a variable number of identical datatype arguments.
Note that a method may have only one "params" modifier. The params modifier needs to be in the last argument.

C# Example
static int totalruns(params int[] runs)
{
  int score = 0;
  for(int x=0; x  &nsbp;score+=runs[x];
 return score;
}

Further, from the calling function, we may pass the scores of each batsman as below...

score = totalruns(12,36,0,5,83,25,26);


4) ref - The argument is given a value by the caller, where data is passed by reference. This value may optionally be reset in the called method. Note that even if NO value is set in the called method for the ref attribute, no compiler error is raised.

Protected Internal  Array  Sort Array  Throw  Multiple Catch  Polymorphism  Inheritance  Session Viewstate  Autogenerate  ReadOnly  Sealed Class  Sealed Method  Multiple Interfaces  Overloading  Overloaded Constructors  Generics  Main  Case Sensitive  Console  Specifier  Return Type  SetCommandLineArgs  System Environment  New  Default Values of Types Compiler Error Constant Variable Const Const - ReadOnly Parameter Modifier Out Ref Interface Interface Reference, is, as System.Collection

More Interview Questions...