Passing ref-types by value
using System;
class Person
{
public string fullName;
public int age;
public Person(string n, int a)
{
fullName = n;
age = a;
}
public void PrintInfo()
{
Console.WriteLine("{0} is {1} years old", fullName, age);
}
}
class MainClass
{
public static void SendAPersonByValue(Person p)
{
p.age = 99;
p = new Person("TOM", 999);
}
public static void Main()
{
Person fred = new Person("Fred", 12);
fred.PrintInfo();
SendAPersonByValue(fred);
fred.PrintInfo();
}
}
Fred is 12 years old
Fred is 99 years old
Value types are passed by value
using System;
class Test {
/* This method causes no change to the arguments used in the call. */
public void noChange(int i, int j) {
i = i + j;
j = -j;
}
}
class MainClass {
public static void Main() {
Test ob = new Test();
int a = 15, b = 20;
Console.WriteLine("a and b before call: " +
a + " " + b);
ob.noChange(a, b);
Console.WriteLine("a and b after call: " +
a + " " + b);
}
}
a and b before call: 15 20
a and b after call: 15 20