In C#, I know that by default, any parameters passed into a function would be by copy, that\'s, within the function, there is a local copy of the parameter. But, what about when
I found the other examples unclear, so I did my own test which confirmed that a class instance is passed by reference and as such actions done to the class will affect the source instance.
In other words, my Increment method modifies its parameter myClass everytime its called.
class Program
{
static void Main(string[] args)
{
MyClass myClass = new MyClass();
Console.WriteLine(myClass.Value); // Displays 1
Increment(myClass);
Console.WriteLine(myClass.Value); // Displays 2
Increment(myClass);
Console.WriteLine(myClass.Value); // Displays 3
Increment(myClass);
Console.WriteLine(myClass.Value); // Displays 4
Console.WriteLine("Hit Enter to exit.");
Console.ReadLine();
}
public static void Increment(MyClass myClassRef)
{
myClassRef.Value++;
}
}
public class MyClass
{
public int Value {get;set;}
public MyClass()
{
Value = 1;
}
}