<T> 형태의 키워드를 이용하여 제너릭을 선언함<T> 대신 구체적인 자료형을 넣어준다.class Stack<T>
{
}
Stack<int> intStack = new Stack<int>();
// 제너릭 클래스 선언 예시
class Stack<T>
{
private T[] elements;
private int top;
public Stack()
{
elements = new T[100];
top = 0;
}
public void Push(T item)
{
elements[top++] = item;
}
public T Pop()
{
return elements[--top];
}
}
static void Main(string[] args)
{
// 제너릭 클래스 사용 예시
Stack<int> intStack = new Stack<int>();
intStack.Push(1);
intStack.Push(2);
intStack.Push(3);
Console.WriteLine(intStack.Pop());
}
class Pair<T1, T2>
{
public T1 First { get; set; }
public T2 Second { get; set; }
public Pair(T1 first, T2 second)
{
First = first;
Second = second;
}
public void Display()
{
Console.WriteLine($"First: {First}, Second: {Second}");
}
}
Pair<int, string> pair1 = new Pair<int, string>(1, "One");
pair1.Display();
Pair<double, bool> pair2 = new Pair<double, bool>(3.14, true);
pair2.Display();
// 출력
First: 1, Second: One
First: 3.14, Second: True
class Person
{
// out 키워드 사용 예시
static void Divide(int a, int b, out int quotient, out int remainder)
{
quotient = a / b;
remainder = a % b;
}
// ref 키워드 사용 예시
static void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
static void Main(string[] args)
{
int quotient, remainder;
Divide(7, 3, out quotient, out remainder);
Console.WriteLine($"{quotient}, {remainder}");
int x = 1, y = 2;
Swap(ref x, ref y);
Console.WriteLine($"{x}, {y}");
}
// 출력
2, 1
2, 1
값의 변경 가능성
ref 매개변수를 사용하면 메서드 내에서 해당 변수의 값을 직접 변경할 수 있다. 이는 예기치 않은 동작을 초래할 수 있으므로 주의 필요
성능 이슈
ref 매개변수는 값에 대한 복사 없이 메서드 내에서 직접 접근할 수 있기 때문에 성능상 이점이 있다. 그러나 너무 많은 매개변수를 ref로 전달하면 코드의 가독성이 떨어지고 유지보수가 어려워질 수 있다. 적절한 상황에서 ref를 사용하는 것이 좋음
변수 변경 여부 주의
out 매개변수는 메서드 내에서 반드시 값을 할당해야 함. 따라서 out 매개변수를 전달할 때 해당 변수의 이전 값이 유지되지 않으므로 주의 필요