본문 바로가기

C#

[C#] 참조 매개변수 ref

 

    class Program
    {
        static void Main(string[] args)
        {

            new Lesson();
        }
    }

	class Lesson
	{
		public Lesson()
		{
			string a = "Good", b = "Bad";

			System.Console.WriteLine($"{a} {b}");			
			Swap(ref a, ref b);	
			System.Console.WriteLine($"{a} {b}");

			int c = 0, d = 1;
			System.Console.WriteLine($"{c} {d}");
			Swap(ref c, ref d);
			System.Console.WriteLine($"{c} {d}");

		}

		// 참조 매개변수 string
		public static void Swap(ref string a, ref string b)
		{
			string t = a;
			a = b;
			b = t;
		}

		// 참조 매개변수 int
		public static void Swap(ref int a, ref int b)
		{
			int t = a;
			a = b;
			b = t;
		}

	}

출력결과

 

  • ref

매개변수 앞에 ref 를 붙여 주면 매개변수 전달 시 값 형식이 아닌 참조 형식으로 전달됨.

ex)

void method(ref int a)

void method(ref string a)

void method(ref ushort a)

...

 

 

2023.10.10 - [C#] - [C#] in 매개변수

 

[C#] in 매개변수

class Program { static void Main(string[] args) { new Lesson(); } } class Lesson { public Lesson() { int num1 = 100; int num2 = 200; print(num1, num2); } // in 매개변수 int public static void print(in int num1, in int num2) { System.Console.WriteLine($

bysik1109.tistory.com

 

2023.10.10 - [C#] - [C#] out 매개변수

 

[C#] out 매개변수

class Program { static void Main(string[] args) { new Lesson(); } } class Lesson { public Lesson() { string a, b; Init(out a, out b); System.Console.WriteLine($"{a} {b}"); } // out 매개변수 string public static void Init(out string a, out string b) { a

bysik1109.tistory.com

 

 

'C#' 카테고리의 다른 글

[C#] in 매개변수  (1) 2023.10.10
[C#] out 매개변수  (2) 2023.10.10
[C#] 파일 삭제  (0) 2023.10.07
[C#] 폴더 (디렉토리) 삭제  (0) 2023.10.07
[C#] 파일 이동, 이름 변경  (0) 2023.10.07