ASP.NET C#

매개변수 키워드

ToKor 2021. 1. 6. 02:06

ref, out, params

- ref: 외부에서 변수 초기화, 함수내에서 변수를 업데이트하면 외부에서도 변함

- out: 외부에서 변수 초기화 하지않음. 외부에서 선언한 변수의 값은 모두 무시됨, 함수내부의 여러값을 리턴할때 사용

- params: 매개변수를 가변성있게 만듬

using System;

namespace Example
{
	public class Program
	{
		private static int RefMethod(ref int a, int b)
		{
			a *= 100;
			b *= 100;
			return b;
		}
		private static void FlexMethod(out int a, out string msg)
		{
			a = 100;
			msg = "Done";
		}
		
		public static void Main(string[] args)
		{
			int a = 3;
			int b = 7;
			string msg = "Ready";
			
			// RefMethod의 ref를 통해 외부선언변수의 초기화가 이루어짐
			int refValue = RefMethod(ref a, b);
			Console.WriteLine("RefMethod return = {0}", refValue);
			Console.WriteLine("a = {0}", a);
			Console.WriteLine("b = {0}", b);
			
			// FlexMethod 를 통해 a, msg 값이 초기화 됨, 복수로 리턴함
			FlexMethod(out a, out msg);
			Console.WriteLine("a = {0}", a);
			Console.WriteLine("msg = {0}", msg);
			
			Console.WriteLine("Press any key");
			Console.ReadLine();
		}
	}
}	
RefMethod return = 700  // 함수의 리턴값
a = 300  // 외부에서도 값이 변함
b = 7  // 외부(변수)에서의 값 변화 없음

a = 100  // 외부값무시, 새롭게 초기화됨
msg = Done  // 외부값무시, 새롭게 초기화됨
public static void paramsMethod(params int[] list)
paramsMethod(1,2,3);
paramsMethod(1,2,3,4,5,6,7);

public static void paramsMethod(params string[] args)
paramsMethod("hello", "world");
paramsMethod("helloo", "my", "world");

public static void paramsMethod(params object[] obj)
paramsMethod("this year", "is", 2021, "last year", "is", 2020);