How to pass reference (by ref) type parameters in C#

1 Answer

0 votes
using System;

namespace functions_by_ref___ref
{
	class Class1
	{
		static void Main(string[] args)
		{
			int x = 4, y = 12, z = 10;

			Swap(x,y);
			Console.WriteLine("Swap: x = {0}, y = {1}", x, y); // Swap: x = 4, y = 12
			ref_Swap(ref x, ref y);
			Console.WriteLine("ref_Swap: x = {0}, y = {1}", x, y); // ref_Swap: x = 12, y = 4
			ref_f1(ref x, y, ref z);
			Console.WriteLine("ref_f1: x = {0}, y = {1}, z = {2}", x, y, z); 
            // ref_f1: x = 1, y = 4, z = 3
			ref_f2(ref x, y);
			Console.WriteLine("ref_f2: x = {0}, y = {1}", x, y); // ref_f2: x = 1000, y = 4
			ref_f3(x, ref y);
			Console.WriteLine("ref_f3: x = {0}, y = {1}", x, y); // ref_f3: x = 1000, y = 9000
		}
		static void Swap(int x, int y)
		{
			int tmp;

			tmp=x;
			x=y;
			y=tmp;
		}
		static void ref_Swap(ref int x, ref int y)
		{
			int tmp;

			tmp=x;
			x=y;
			y=tmp;
		}
		static void ref_f1(ref int a, int b, ref int c)
		{
			a = 1;
			b = 2;
			c = 3;
		}
		static void ref_f2(ref int a, int b)
		{
			a = 1000;
			b = 2000;
		}
		static void ref_f3(int a, ref int b)
		{
			a = 8000;
			b = 9000;
		}
	}
}



answered Jul 25, 2014 by avibootz

Related questions

2 answers 180 views
1 answer 130 views
130 views asked Nov 27, 2020 by avibootz
1 answer 215 views
215 views asked Aug 5, 2014 by avibootz
2 answers 224 views
1 answer 87 views
87 views asked Dec 19, 2024 by avibootz
1 answer 116 views
...