27call by Value Out

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 16

http://www.vidyanidhi.

com/
ketkiacharya.net@gmail.com

C# Laguage
Call By Value and Call By Reference

Ketki Acharya
From: SM VITA ATC of CDAC
9769201036
ketkiacharya.net@gmail.com

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


// Simple types are passed by value.

Call by value
using System;

class Test
{
/* This method causes no change to the arguments
When you pass primitive type in a function another j
used in the call. */ i
memory block get created and data get copied to public void noChange(int i, int j)
new memory block. So if you make some changes {
15 20 20 25
i += 5;
to the parameter in a function original data does not j += 5;
get affected see the diagram }

}
class CallByValue
{
public static void Main()
{

Test ob = new Test();

int a = 15, b = 20;


a b Console.WriteLine("a and b before call: " + a + " " + b);//15 20

15 20 ob.noChange(a, b);

Console.WriteLine("a and b after call: " + a + " " + b);//15 20


}
}

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Passing object in a // Objects are reference but pass by as value.

function is call by using System;


class Test

value {
public int a, b;
In call by value when you pass data it get copied
to another memory block. But when you pass public Test(int i, int j)
{
reference in a function another memory block a = i;
get created, since reference variable is holding b = j;
}
Reference(arrow) , same reference (arrow ) /* Pass an object. Now, ob.a and ob.b in object
get copied used in the call will be changed. */
So now both ob and obj pointing to same public void change(Test obj)
{
Memory bloc. obj.a += 5;
obj.b += 5;
}
obj }

class CallByRef
{
public static void Main()
{
ob a=15 20 Test ob = new Test(15, 20);
b=20 25
Console.WriteLine("ob.a and ob.b before call: " + ob.a + " " + ob.b);
ob.change(ob);
Console.WriteLine("ob.a and ob.b after call: " + ob.a + " " + ob.b);
}
}

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


// Use ref to pass a value type by reference.
Call by Reference using System;

class RefTest
When you pass primitive type in a function using {
ref /* This method changes its arguments.
Key another memory block does not get created Notice the use of ref. */
public void sqr(ref int i)
but
{
It is just another name to same memory block. i = i * i;
So if you make some changes to the parameter in a }
function original data will get modified }
see the diagram class RefDemo
Here is one important point to understand about {
ref: An argument passed by ref must be assigned a public static void Main()
{
value prior to the call. The reason is that the
RefTest ob = new RefTest();
method that receives such an argument assumes 10
a
that the parameter refers to a valid value. 100 int a = 10;
i Console.WriteLine("a before call: " + a);

ob.sqr(ref a); // notice the use of ref

Console.WriteLine("a after call: " + a);


When you pass data using ref key word we are
}
using concept of pass(call) by reference }

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


// Swap two values.

Swap two number using System;


class ValueSwap
{ // This method now changes its arguments.
public void Swap(ref int a, ref int b)
{ int t;
t = a;
a = b;
b = t;
}
}
class ValueSwapDemo
{ static void Main()
{ ValueSwap ob = new ValueSwap();
int x = 10, y = 20;
Console.WriteLine("x and y before call: " + x + " " + y);
ob.Swap(ref x, ref y);
Console.WriteLine("x and y after call: " + x + " " + y);
}
}
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
// Objects are reference but pass by as value.

Call by Reference using System;


class Test
{
public int a, b;
When you pass object in a function using ref public Test(int i, int j)
Key another memory block does not get created {
a = i;
but b = j;
It is jut another name to same memory block. So if }
/* Pass an object. Now, ob.a and ob.b in object
you make some changes to the parameter in a used in the call will be changed. */
function original data will get modified public void change(ref Test obj)
{
see the diagram obj.a += 5;
obj.b += 5;
}
}

class CallByRef
{
public static void Main()
{
ob Test ob = new Test(15, 20);
a=15 20 Console.WriteLine("ob.a and ob.b before call: " + ob.a + " " + ob.b);
obj b=20 25
ob.change(ref ob);

Console.WriteLine("ob.a and ob.b after call: " + ob.a + " " + ob.b);
}
}

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Call by // Use out.

Reference
using System;
class Decompose {
Out is also pass data by reference /* Decompose a floating-point value into its
integer and fractional parts. */
the out parameter. public int parts(double n, out double frac) {
An out parameter is similar to a ref parameter with int whole;
this one exception: It can only be used to pass a value
whole = (int) n;
out of a method.
frac = n - whole; // pass fractional part back through frac
return whole; // return integer portion
It is not necessary (or useful) to give the variable
}
used as an out parameter an initial value prior to
}
calling the method.
class UseOut {

The method will give the variable a value. public static void Main() {

Furthermore, inside the method, an out parameter is Decompose ob = new Decompose();


f
considered unassigned; that is, it is assumed to have int i; 0.125
frac
no initial value. double f; //observed f is not initialized
i = ob.parts(10.125, out f);
This implies that the method must assign the Console.WriteLine("Integer portion is " + i);
parameter a value prior to the method’s Console.WriteLine("Fractional part is " + f);
termination. Thus, after the call to the method, an }
out parameter will contain a value. }

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


TASK
• Write a method which will return sum of digit and using out variable let
it send count of digit also.
• Eg. input 123 return(6) in out variable (3)

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Variable length of arguments // public static void Write(string format, params object[] arg);
using System;
class Min
{ public int minVal(params int[] nums)
{
int m;
Params is a key word which will accept if (nums.Length == 0)
parameter as array so that it will work {
Console.WriteLine("Error: no arguments.");
irrespective of the number of data pass while return 0;
calling function. }
m = nums[0];
Think about for (int i = 1; i < nums.Length; i++)
if (nums[i] < m)
public static void Write(string m = nums[i];

format, params object[] arg); return m;


}
}
We don’t know how many variable class ParamsDemo
{
user is going to print using write public static void Main()
method that is why signature of { Min ob = new Min();
int min;
write method has used params key int a = 10, b = 20;

word // call with two values


0 1 min = ob.minVal(a, b);
Console.WriteLine("Minimum is " + min);
10 20 // call with 3 values
min = ob.minVal(a, b, -1);
Console.WriteLine("Minimum is " + min);
0 1 2
// call with 5 values
10 20 -1 min = ob.minVal(18, 23, 3, 14, 25);
Console.WriteLine("Minimum is " + min);
// can call with an int array, too
int[] args = { 45, 67, 34, 9, 112, 8 };
min = ob.minVal(args);
USM’s Shriram Mantri Console.WriteLine("Minimum
Vidyanidhi Info Tech Academy is " + min);
Method returning Array
// Return an array.

using System;
class Factor
{
/* Return an array containing the factors of num.
On return, numfactors will contain the number of
factors found. */

public int[] findfactors(int num, out int numfactors)


{

int[] facts = new int[10]; // size of 10 is arbitrary

new Factor(); int i, j;


public int[] findfactors int num
f // find factors and put them in the facts array
for (i = 1, j = 0; i <= num; i++)
12 if ((num % i) == 0)
{
facts[j] = i;
j++;
1 2 3 4 6 12 0 0 0 0 }

numfactors = j;
return facts;
}
int[] }
factS
class FindFactors
{
{numfactors} public static void Main()
{
Factor f = new Factor();
numfactors int numfactors;
int[] factors;

factors = f.findfactors(12, out numfactors);


int[] factors
Console.WriteLine("Factors for 12 are:{0} ", numfactors);
0 for (int i = 0; i < numfactors; i++)

6 Console.Write(factors[i] + " ");

Console.WriteLine();
}
}
USM’s Shriram Mantri Vidyanidhi Info Tech Academy
TASK
Write a method which will accept two number and return all even
number between it as array and also give count in out variable.
Int count=
Int [] result=Dojob(5,30)

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Default Agument static void mycall(string message, int age = 25)
using System; {
Console.Beep();
namespace Named_param Console.WriteLine(" {0}", message);
{ Console.WriteLine(": {0}", age);
class Program }
{
static void Main(string[] args)
{ }
mycall("vita");
mycall("vita", 20); }
Console.ReadLine();
}

// Error! The default value for an optional arg must be known // at compile time!

static void EnterLogData(string message,string owner = "Programmer", DateTime timeStamp = DateTime.Now)


{
Console.Beep();
Console.WriteLine("Error: {0}", message);
Console.WriteLine("Owner of Error: {0}", owner);
Console.WriteLine("Time of Error: {0}", timeStamp);
}
/* This will not compile, as the value of the Now property of the DateTime class is resolved at runtime,
not compile time.*/

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


using System;

namespace ConsoleAppdemo_val
{
Call by Value class Employee
{
eid=1
int a,b; public int eid;
public float sal;
e1
sal=50000
b
a=5; public Employee(int id, float salary)
{
30000

5 eid = id;
b=a; sal = salary; e2
}

a }
class Program
{
5 static void Main(string[] args)
{
Employee e1 = new
Employee(1,50000);
Employee e2;
e2 = e1;
Console.WriteLine("Hello World!");

}
}
}

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


Named Parameter

using System;
using System.Collections.Generic;
using System; using System.Linq;
using System.Collections.Generic; using System.Text;
using System.Linq; using System.Threading.Tasks;
using System.Text;
using System.Threading.Tasks; namespace ConsoleApplication4
{
namespace ConsoleApplication4 class Program
{ {
class Program static void Main(string[] args)
{ {
static void Main(string[] args) DisplayFancyMessage( "Wow! Very Fancy indeed!", 50, name:"raj");
{ // DisplayFancyMessage( "geeta", message: "hello",50);
DisplayFancyMessage(message: "Wow! Very Fancy indeed!", number:50, name:"raj"); Console.ReadLine();
DisplayFancyMessage(name: "geeta", number: 50, message: "hello");
Console.ReadLine(); }

} static void DisplayFancyMessage( string message,int number, string name,)


{
static void DisplayFancyMessage(int number, string name, string message) Console.WriteLine("{0},{1},{2}",number,name,message );
{
Console.WriteLine("{0},{1},{2}",number,name,message ); }

} }
}
}
}

One minor gotcha regarding named arguments is that if you begin to invoke a method using

positional parameters, they must be listed before any named parameters. In other words,
named arguments must always be packed onto the end of a method call.

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


using System;

namespace ConsoleAppADONETSTUDENTS
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Methods *****");
DisplayFancyMessage(message: "Wow! Very Fancy indeed!",textColor: ConsoleColor.DarkRed,
backgroundColor: ConsoleColor.White);

DisplayFancyMessage(backgroundColor: ConsoleColor.Green, message: "Testing...",


textColor: ConsoleColor.DarkBlue);
Console.ReadLine();
}
static void DisplayFancyMessage(ConsoleColor textColor, ConsoleColor backgroundColor, string message)
{

// Set new colors and print message.


// This is OK, as positional args are listed before named args.
Console.ForegroundColor = textColor; DisplayFancyMessage(ConsoleColor.Blue,
Console.BackgroundColor = backgroundColor; message: "Testing...",
backgroundColor: ConsoleColor.White);
Console.WriteLine(message);
} // This is an ERROR, as positional args are listed after named
args.
DisplayFancyMessage(message: "Testing...",
} backgroundColor: ConsoleColor.White,
ConsoleColor.Blue);
}

USM’s Shriram Mantri Vidyanidhi Info Tech Academy


you might still be wondering when you would ever want to use this language feature. After all, if you need to specify three
arguments to a method, why bother flipping around their position?

Well, as it turns out, if you have a method that defines optional arguments, this feature can actually be really helpful.
namespace ConsoleApp2
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Methods *****");

DisplayFancyMessage(textColor: ConsoleColor.DarkRed,backgroundColor: ConsoleColor.White, message: "Wow! Very Fancy


indeed!");

DisplayFancyMessage(backgroundColor: ConsoleColor.Green, textColor: ConsoleColor.DarkBlue, message: "Testing...");


DisplayFancyMessage(message:"Testing...");
DisplayFancyMessage();
Console.ReadLine();
}

static void DisplayFancyMessage(ConsoleColor textColor = ConsoleColor.Blue, ConsoleColor backgroundColor = ConsoleColor. White,


string message = "Test Message"
)
{
// Set new colors and print message.
Console.ForegroundColor = textColor;
Console.BackgroundColor = backgroundColor;
Console.WriteLine(message);

} USM’s Shriram Mantri Vidyanidhi Info Tech Academy

You might also like