Favicon

Out generic modifier

Peponi11/28/20242m

C#
SyntaxKeywordModifier

1. Introduction

out 키워드는 참조 형식 매개 변수를 공변으로 할 수 있는 제네릭 한정자로 제네릭 인터페이스 선언 및 대리자에 사용할 수 있다.

공변성을 부여하여 암시적 변환에 의해 파생 형식의 사용이 가능해진다.

2. Example

interface
public interface InterfaceA<out T>
{
    Type GetType() => typeof(T);
}
 
public class ClassA<T> : InterfaceA<T>
{ }
 
private static void Main(string[] args)
{
    InterfaceA<object> a = new ClassA<object>();
    InterfaceA<List<int>> b = new ClassA<List<int>>();
    a = b;
 
    Console.WriteLine(a.GetType());     // ClassA`1[System.Collections.Generic.List`1[System.Int32]]
}
delegate
public delegate T DelegateA<out T>();
 
public static object GetObject() => new object();
 
public static List<int> GetInts() => new List<int>();
 
private static void Main(string[] args)
{
    DelegateA<object> A = GetObject;
    DelegateA<List<int>> B = GetInts;
    A = B;
 
    Console.WriteLine(A());     // System.Collections.Generic.List`1[System.Int32]
}

3. 참조 자료