📕매개변수 한정자(ref, out, in)
📖매개변수 한정자란?
매개변수 한정자는 메서드에 전달하는 매개변수의 전달 방식을 지정하기 위해 사용한다. 매개변수 한정자로는 ref, out, in가 있다.
각 한정자는 다음과 같은 상황에서 쓰인다.
- ref : 전달된 매개변수를 메서드에서 수정하고 싶을 때
- in : 전달된 매개변수가 메서드에서 수정되지 않아야 할 때
- out : 전달된 매개변수가 반드시 메서드에서 수정되어야 할 때
ref와 in는 메서드에 전달하기 전 초기화 되어야 하지만 out는 메서드에서 초기화 된다.
💡매개변수 한정자를 쓰지 않고 매개변수를 전달하면 값 형식으로 전달된다.
📌ref 한정자
메서드 내에서 수정된 매개변수의 값이 메서드 외부에 반영되게 하려면 매개변수를 참조 형식으로 전달해야 한다. 이때 사용하는 한정자가 ref이다.
class ReferenceTypeExample
{
static void Enroll(ref Student student)
{
// With ref, all three lines below alter the student variable outside the method.
student.Enrolled = true;
student = new Student();
student.Enrolled = false;
}
static void Main()
{
var student = new Student
{
Name = "Susan",
Enrolled = false
};
Enroll(ref student);
// student.Name is now null since a value was not passed when declaring new Student() in the Enroll method
// student.Enrolled is now false due to the ref modifier
}
}
public class Student {
public string Name {get;set;}
public bool Enrolled {get;set;}
}
위 코드에서 student.Name의 값은 null이다. Enroll 메서드에서 student의 기본 생성자를 호출하면서 모든 값을 초기화했기 때문이다. 원래대로라면 Enroll 메서드의 변경 사항은 외부에 반영되지 않지만 위 코드에서는 ref를 사용했기 때문에 student의 값이 변경되었다.
📌out 한정자
out을 사용할 때는 메서드에 전달되는 매개변수를 메서드 내에서 초기화해야 한다. ref와 마찬가지로 메서드 내의 모든 변경 사항은 메서드 외부에 반영된다.
class ReferenceTypeExample
{
static void Enroll(out Student student)
{
//We need to initialize the variable in the method before we can do anything
student = new Student();
student.Enrolled = false;
}
static void Main()
{
Student student;
Enroll(out student); // student will be equal to the value in Enroll. Name will be null and Enrolled will be false.
}
}
public class Student {
public string Name {get;set;}
public bool Enrolled {get;set;}
}
📌in 한정자
in으로 전달한 매개변수는 메서드에서 수정될 수 없다. 값이 수정되지 않을 것임을 미리 알려줌으로써 성능을 향상시킨다.
class ReferenceTypeExample
{
static void Enroll(in Student student)
{
// With in assigning a new object would throw an error
// student = new Student();
// We can still do this with reference types though
student.Enrolled = true;
}
static void Main()
{
var student = new Student
{
Name = "Susan",
Enrolled = false
};
Enroll(student);
}
}
public class Student
{
public string Name { get; set; }
public bool Enrolled { get; set; }
}
🔖참조
https://www.pluralsight.com/guides/csharp-in-out-ref-parameters
C# Tutorial: Using in, out, and Ref with Parameters | Pluralsight
Using the out modifier, we initialize a variable inside the method. Like ref, anything that happens in the method alters the variable outside the method. With ref, you have the choice to not make changes to the parameter. When using out, you must initializ
www.pluralsight.com
'C#' 카테고리의 다른 글
[C#] 딕셔너리(Dictionary) (0) | 2022.07.08 |
---|---|
[C#]리플렉션(Reflection)과 어트리뷰트(Attribute) (0) | 2022.07.06 |
제네릭(Generics)이란? (0) | 2022.06.24 |
구조체(Struct)와 클래스(Class) (0) | 2022.06.17 |
생성자 (0) | 2022.06.17 |