프로그래밍 언어/C#

C# _ Discard (변수 무시)

ShovelingLife 2023. 6. 7. 11:13

필요한 이유

  • 별도의 변수를 선언 할 필요가 없다. 또한 discards를 사용하면 메모리 할당을 줄일 수 있다.
  • 코드의 의도를 투명하게 만들고 가독성과 유지 관리성을 향상시키는데 도움된다.

예제 코드

switch를 사용한 패턴 매칭

class Program
{
    static void ProvideString(string statement) =>
        Console.WriteLine(statement switch
        {
            "x" => "hello, x world",
            null => "hello, null world",
            _ => "hello, world"
        });


    static void Main(string[] args)
    {
        ProvideString("x");
        ProvideString(null);
        ProvideString("");
    }
}

out 매개 변수를 사용한 메서드 호출

string[] dateStrings = {"05/01/2018 14:57:32.8", "2018-05-01 14:57:32.8",
                      "2018-05-01T14:57:32.8375298-04:00", "5/01/2018",
                      "5/01/2018 14:57:32.80 -07:00",
                      "1 May 2018 2:57:32.8 PM", "16-05-2018 1:00:32 PM",
                      "Fri, 15 May 2018 20:10:57 GMT" };
foreach (string dateString in dateStrings)
{
    if (DateTime.TryParse(dateString, out _))
        Console.WriteLine($"'{dateString}': valid");
    else
        Console.WriteLine($"'{dateString}': invalid");
}

독립 실행형 무시 항목

private static async Task ExecuteAsyncMethods()
{
    Console.WriteLine("About to launch a task...");
    _ = Task.Run(() =>
    {
        var iterations = 0;
        for (int ctr = 0; ctr < int.MaxValue; ctr++)
            iterations++;
        Console.WriteLine("Completed looping operation...");
        throw new InvalidOperationException();
    });
    await Task.Delay(5000);
    Console.WriteLine("Exiting after 5 second delay");
}
private static async Task ExecuteAsyncMethods()
{
    Console.WriteLine("About to launch a task...");
    // CS4014: Because this call is not awaited, execution of the current method continues before the call is completed.
    // Consider applying the 'await' operator to the result of the call.
    Task.Run(() =>
    {
        var iterations = 0;
        for (int ctr = 0; ctr < int.MaxValue; ctr++)
            iterations++;
        Console.WriteLine("Completed looping operation...");
        throw new InvalidOperationException();
    });
    await Task.Delay(5000);
    Console.WriteLine("Exiting after 5 second delay");   
 }

유용한 식별자로도 사용이 가능

private static void ShowValue(int _)
{
   byte[] arr = { 0, 0, 1, 2 };
   _ = BitConverter.ToInt32(arr, 0);
   Console.WriteLine(_);
}
 // The example displays the following output:
 //       33619968

형식 안전성 위반으로 컴파일 에러 발생

private static bool RoundTrips(int _)
{
   string value = _.ToString();
   int newValue = 0;
   _ = Int32.TryParse(value, out newValue);
   return _ == newValue;
}
// The example displays the following compiler error:
//      error CS0029: Cannot implicitly convert type 'bool' to 'int'

동일한 변수명으로 선언할 수 없습니다 에러 발생

public void DoSomething(int _)
{
 var _ = GetValue(); // Error: cannot declare local _ when one is already in scope
}
// The example displays the following compiler error:
// error CS0136:
//       A local or parameter named '_' cannot be declared in this scope
//       because that name is used in an enclosing local scope
//       to define a local or parameter

out으로 받지만 호출자는 사용할 필요가 없는 경우

public void Main()
{
    string str = "abc";
 
    if (int.TryParse(str, out var intResult) == false) // intResult는 쓸모가 없음.
    {
        Console.WriteLine("이것은 int 다.");
        return;
    }
 
    if (float.TryParse(str, out var floatResult) == false) // floatResult는 쓸모가 없음.
    {
        Console.WriteLine("이것은 float 이다.");
        return;
    }
 
    Console.WriteLine("Parse가 가능하다.");
}
public void Main()
{
    string str = "abc";
 
    if (int.TryParse(str, out _) == false) // _는 변수가 아니라서 밑에서 계속 쓸 수 있다.
    {
        Console.WriteLine("이것은 int 다.");
        return;
    }
 
    if (float.TryParse(str, out _) == false)
    {
        Console.WriteLine("이것은 float 이다.");
        return;
    }
 
    Console.WriteLine("Parse가 가능하다.");
}

튜플에서도 사용 가능하다

public (bool, string) DoTest()
{
    return (true, "Hello world!");
}
 
public void Main()
{
    var (_, stringResult) = DoTest(); // bool은 버리고 string만 쓰자.
    Console.WriteLine(stringResult);
}

 

출처 : https://jettstream.tistory.com/49

출처 : https://developstudy.tistory.com/94