본문 바로가기
🖥️/C#

[C#] switch문과 switch식

by HanaV 2023. 8. 16.
728x90

switch문

switch문은 아래와 같이 case에 맞는 값을 지정해 줄 수 있다.

int score = 95; string grade = "";

int score = (int)(Math.Truncate(input/10.0) * 10; //1의 자리를 버림

switch (score)
{
    case 90:
        grade = "A";
        break;
    case 80:
        grade = "B";
        break;
    case 70:
        grade = "C";
        break;
    case 60:
        grade = "D"; 
        break;
    default:
    	grade = "F";
}

 

switch 식

switch문은 break;나 case: 등 반복되는 코드가 많은 것을 볼 수 있다. 이때, switch 식을 사용하면 코드의 길이를 줄이고 가독성을 높일 수 있다.

int score = 90;
string grade = (int)(Math.Truncate(score / 10.0) * 10) switch
{
    90 => "A",
    80 => "B",
    70 => "C",
    60 => "D",
    _ => "F"
};
728x90

"); wcs_do();