As we know parameters allow information to be passed in and out of a method.
When you define method, you can include list of parameters in parentheses.
Declaring Methods with parameters
Each parameter has a type and a name. u can declare parameters by placing parameter declaration inside parentheses. A syntax that is used to declare parameters is similar to the syntax that is used to declare local variables.
The syntax for declaring parameters inside methods
void Method(int n, string y)
{
// body.
}
the preceding code declares the method (Method) with out parameters and y. The first parameter is of type int and 2nd of type string.
Calling methods with Parameters
value type:
values r some time passed in parameters, therefore, the data can be transferred into the method but cannot be transferred out.
Reference type:
These r some times called In/Out parameters, therfore, the data can be transferred into the method and out again.
Pass Parameter by value
The simplest definition of a value parameter is the data type name followed by a variable name.
When a method is called, a new storage location is created for each value parameter. The values of the corresponding expressions are copied into them. The expressions supplied for each value parameter must be similar to the declaration of the value parameter or it must be a type that cane be implicitly converted to the value type .
example :
class calculatorpass parameter by reference
{
void Addone(int var)
{
var++;
}
public static void Main(string [] arg)
{
Calculator Cal=new Calculator();
int number=6;
cal.Addone(number);
Console.WriteLine(number); //.................. Display value 6 .
}
}
A reference parameter is a reference to a memory location of a data member.
Unlike a value parameter, a reference parameter does not create a new storage location., instead reference parameters represents the same location in memory as the variable that is supplied in the method call.
you can declare reference parameter by using the ref keyword before the data type, as shown in the following example:
class Calculator
{
void Addone(ref int var)
{
var++;
}
public static void Main(string [] arg)
{
Calculator obj=new Calculator();
int number =6;
obj.Addone(ref number);
Console.WriteLine(number);//....................Displays value 7.
}
}
Labels: C# Programming
0 Comments:
Subscribe to:
Post Comments (Atom)