- params : 가변수의 argument를 받는다.
- in : by reference로 전달되며, 호출된 함수가 읽을 수만 있다.
- ref : by reference로 전달되며, 호출된 함수가 읽거나 쓸 수 있다.
- out : by reference로 전달되며, 호출된 함수가 쓸 수 있다.
params
params keyword를 사용하므로, method parameters가 arguments의 가변수를 갖는다고 지정할 수 있다. parameter type은 일차원 array어야 한다.
params keyword이후에는 추가 parameters가 허용되지 않는다.
params parameter의 type이 1차원 배열이 아니면 compiler가 에러를 일으킨다.
params parameter와 함께 함수를 호출할때, 다음을 전달할 수 있다.
- array elements type의 comma로 구분된 list
- 특정 type의 array
- No arguments
public class MyClass
{
public static void UseParams(params int[] list)
{
for (int i = 0; i < list.Length; i++)
{
Console.Write(list[i] + " ");
}
Console.WriteLine();
}
public static void UseParams2(params object[] list)
{
for (int i = 0; i < list.Length; i++)
{
Console.Write(list[i] + " ");
}
Console.WriteLine();
}
static void Main()
{
// You can send a comma-separated list of arguments of the
// specified type.
UseParams(1, 2, 3, 4);
UseParams2(1, 'a', "test");
// A params parameter accepts zero or more arguments.
// The following calling statement displays only a blank line.
UseParams2();
// An array argument can be passed, as long as the array
// type matches the parameter type of the method being called.
int[] myIntArray = { 5, 6, 7, 8, 9 };
UseParams(myIntArray);
object[] myObjArray = { 2, 'b', "test", "again" };
UseParams2(myObjArray);
// The following call causes a compiler error because the object
// array cannot be converted into an integer array.
//UseParams(myObjArray);
// The following call does not cause an error, but the entire
// integer array becomes the first element of the params array.
UseParams2(myIntArray);
}
}
/*
Output:
1 2 3 4
1 a test
5 6 7 8 9
2 b test again
System.Int32[]
*/
out parameter modifier
out parameter를 사용하기 위해서는, method definition과 calling method 모두 반드시 out keyword를 사용해야 한다.
int initializeInMethod;
OutArgExample(out initializeInMethod);
Console.WriteLine(initializeInMethod); // value is now 44
void OutArgExample(out int number)
{
number = 44;
}
함수 호출전에 out arguments가 초기화될 필요는 없지만, 함수는 return하기 전에 값을 할당해야 한다.
Declaring out parameters
out arguments와 함께 선언한 함수는 여러 값을 return하는 전형적인 해결방법이다. 비슷한 상황에서 value tuples를 사용하는 것을 고려할 수도 있다.
다음 코드는 out를 사용해 하나의 함수애서 3개의 변수를 반환하는 것을 보여준다. 세번째 argument는 null로 할당되었다.
void Method(out int answer, out string message, out string? stillNull)
{
answer = 44;
message = "I've been returned";
stillNull = null;
}
int argNumber;
string argMessage;
string? argDefault;
Method(out argNumber, out argMessage, out argDefault);
Console.WriteLine(argNumber);
Console.WriteLine(argMessage);
Console.WriteLine(argDefault == null);
// The example displays the following output:
// 44
// I've been returned
// True
Calling a method with an out argument
out argument로 전달하기 전에 변수를 별도의 구문으로 선언해야 한다.
아래 코드에서 TryParse에 전달하기 전에 number라는 변수를 선언했다.
string numberAsString = "1640";
int number;
if (Int32.TryParse(numberAsString, out number))
Console.WriteLine($"Converted '{numberAsString}' to {number}");
else
Console.WriteLine($"Unable to convert '{numberAsString}'");
// The example displays the following output:
// Converted '1640' to 1640
별도 변수 선언하지 않고, 함수 호출의 argument list에서 out variable을 선언할 수도 있다. 더 단순하고, 가독성 있고, 변수값 수정오류를 막을 수 있다.
string numberAsString = "1640";
if (Int32.TryParse(numberAsString, out int number))
Console.WriteLine($"Converted '{numberAsString}' to {number}");
else
Console.WriteLine($"Unable to convert '{numberAsString}'");
// The example displays the following output:
// Converted '1640' to 1640
위 예에서 number함수는 int로 strongly type이다. var와 같은 implicitly typed local 변수도 선언할 수 있다.
string numberAsString = "1640";
if (Int32.TryParse(numberAsString, out var number))
Console.WriteLine($"Converted '{numberAsString}' to {number}");
else
Console.WriteLine($"Unable to convert '{numberAsString}'");
// The example displays the following output:
// Converted '1640' to 1640
out (generic modifier)
generic interfaces와 delegates에서 out keyword를 사용할 수 있으며, out keyword는 type parameter가 covariamt함을 명시한다.
'C#' 카테고리의 다른 글
C#] method signature - generic type, specific type (1) | 2023.09.15 |
---|---|
C# 9.0] init keyword, record, with-expression (0) | 2023.09.05 |
C#] Method Parameters - parameters 전달 (0) | 2023.08.22 |
C#] type, System.Type, System.Reflection (0) | 2023.06.19 |
C#] System.Collections.Immutable (0) | 2023.05.18 |
댓글