Pass by value and Pass by reference

October 19, 2020 | Development

You pass arguments to functions: by value or by reference.

Passing by value means you are passing a copy of the variable, while passing by reference means you are passing the actual variable and any changes will reflect upon it.

Pass by Value and Pass by Reference (Cookie Edition)

using System;
					
public class Program
{
	public static void Main()
	{
		HelloWorld helloWorld = new HelloWorld();
		helloWorld.DoMagic();
	}
}

public class HelloWorld {
	private int x = 5;

	public HelloWorld() { }

	public void DoMagic()
	{
        // Comment here
		DoSomethingByValue(x);
		// DoSomethingByReference(ref x);
	}

	public void DoSomethingByValue(int x)
	{
		Console.WriteLine("This will print 6");
		x++;
		Console.WriteLine(x);

		Console.WriteLine("This will print 5");
		Console.WriteLine(this.x);
	}

	public void DoSomethingByReference(ref int x)
	{
		Console.WriteLine("This will print 6");
		x++;
		Console.WriteLine(this.x);
	}
}

*in C# you can pass by reference using the ref keyword


~no comments
~post a comment: