When keyword
Peponi │ 12/17/2024 │ 2m
C#
SyntaxKeywordwhen
When keyword
12/17/2024
2m
Peponi
C#
SyntaxKeywordwhen
1. Introduction
when
키워드는 필터 조건을 지정하는 데 사용한다.
2. Example
when
키워드는 아래와 같이 사용한다.
public class Foo
{
public static void RaiseException()
{
throw new NotImplementedException("My exception");
}
}
private static void Main()
{
try
{
Foo.RaiseException();
}
catch (Exception e) when (e is NotImplementedException)
{
Console.WriteLine($"Exception has been occurred - {e}");
}
}
/* output:
Exception has been occurred - System.NotImplementedException: My exception
at ConsoleApp1.Program.Foo.RaiseException() in ...
*/
public static class IntHelper
{
public static void PositiveCompare(int a, int b)
{
switch ((a, b))
{
case ( > 0, > 0) when a > b:
Console.WriteLine($"{a} is bigger than {b}");
break;
case ( > 0, > 0) when a < b:
Console.WriteLine($"{b} is bigger than {a}");
break;
case ( > 0, > 0) when a == b:
Console.WriteLine($"{a} is same as {b}");
break;
default:
Console.WriteLine("Wrong compare case");
break;
}
}
}
private static void Main()
{
IntHelper.PositiveCompare(1, 2);
}
/* output:
2 is bigger than 1
*/
public static class IntHelper
{
public static int PositiveCompare(int a, int b)
{
return (a, b) switch
{
( > 0, > 0) when a > b => a,
( > 0, > 0) when a < b => b,
( > 0, > 0) when a == b => a,
_ => throw new ArgumentException("Input value must be greater than 0")
};
}
}
private static void Main()
{
Console.WriteLine(IntHelper.PositiveCompare(3, 7));
}
/* output:
7
*/