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);
'ASP.NET C#' 카테고리의 다른 글
상속, abstract, virtual, new, override (0) | 2021.01.08 |
---|---|
static, encapsulation and access modifier (0) | 2021.01.07 |
배열선언 (0) | 2021.01.06 |
메모리구조, 가비지컬렉터 (0) | 2021.01.05 |
Type conversions(형변환) (0) | 2021.01.05 |