What is Call by value and Call by reference in C#
Parameter-we can pass two type of parameter to the method.
Step 1 - First open your visual studio->File->New->Project->console Application->OK->write the program which is below:
see it
- Input parameter
- Out parameter
- Input parameter- This kind of parameter is specify to give the same input to method for calling it.
- Call by value -> In this case when we call the method of any class (which takes some parameter)from main method using object.Then value of parameter in main method will directly copy to theclass method to parameter values respectively. In this case if some changes occurs in values within the method that change not occurs in actual variable .I have full describe this concept through programming which is given below.
- Call by reference -> In this case when we call the method,the reference address of variable is passed to the method.If some changes occurs in values within the method that changes occurs inactual variable.To specify this parameter we use 'ref' Keyword at the time of parameter declaration as well as the calling method.
Step 1 - First open your visual studio->File->New->Project->console Application->OK->write the program which is below:
see it
using System; namespace callbyvalue { class Program { public class employee { public void display( int a, String b) { Console.WriteLine( "Integer value is" + " " +a); Console.WriteLine( " String value is" + " " + b); Console.ReadLine(); } } public class student { public void show( ref String str) { Console.WriteLine( "Enter the value" ); string s = Console.ReadLine(); str = str + s; Console.WriteLine( "value in str variable is" + " " +str); Console.ReadLine(); } } //all class member is called through main method. static void Main( string [] args) { //creating the object of employee class first and implementing the call by value concept. String m = "sunil" ; employee emp = new employee(); emp.display(200,m); Console.WriteLine( "value in variable m is" + " " +m); Console.ReadLine(); //creating the object of employee class first and implementing the call by Reference concept string msg= "Hello" ; student st = new student(); st.show( ref msg); Console.WriteLine( "value in msg is" + " " +msg); //value at address msg will be print,because here address is copy not value thatswhy at same address value will be print Console.ReadLine(); } } }
Step 2 - Now Run the program(press F5).
Output:
|
No comments:
Post a Comment