[C# 문법] C# IF문 줄이기


안녕하세요.

 

오늘은 C# 문법에서 IF문 사용법 줄이는 방법에 대해서 보여드리려고 합니다.

 

모든 방식에 적용 되는 것은 아니고, 단순히 IF, ELSE IF 문이 일정 패턴을 통해 반복되는 경우 줄일 수 있는 부분인 점 참고해 주시기 바랍니다.


 

우선 아래와 같이 IF문이 반복되어 있는 소스코드가 있습니다.

 

중복된 IF, ELSE 


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace IfElseTest

{

    class Program

    {

        static void Main(string[] args)

        {

            string str = string.Empty;

            str = "";

 

            if(str == "하나")

            {

                Console.WriteLine("하나");

            }

            else if(str == "")

            {

                Console.WriteLine("");

            }

            else if (str == "")

            {

                Console.WriteLine("");

            }

            else if (str == "")

            {

                Console.WriteLine("");

            }

            else if (str == "다섯")

            {

                Console.WriteLine("다섯");

            }

        }

    }

}

 

Colored by Color Scripter

cs

 

지금 위와 같이 IF, ELSE IF 구문이 중복돼서 사용되어 진 것을 확인하실 수 있습니다.

 

그럼 이제 위의 구문은 변경해 보도록 하겠습니다.

 

변경된 IF, ELSE IF


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace IfElseTest

{

    class Program

    {

        static void Main(string[] args)

        {

            string str = string.Empty;

            str = "";

 

            string[] arr = { "하나""""""""다섯" };

            int index = 0;

 

            for(int idx = 0; idx < arr.Length; idx++)

            {

                if(str.Contains(arr[idx]))

                {

                    index = idx;

                }

            }

 

            string msg = string.Format("str 값은 : {0} 입니다.", arr[index]);

            Console.WriteLine(msg);

        }

    }

}

 

Colored by Color Scripter

cs

 

실행 결과



위와 같이 배열을 이용하여 중첩된 IF문을 변경해 보았습니다.

 

모든 IF, ELSE IF 문을 위와 같이 변경 할 수 있는 것은 아니고, 반복되는 패턴이 있는 경우에 쉽게 변경이 가능하고 변경이 안되는 경우도 많기 때문에 참고해 주시면 좋겠습니다!


감사합니다.^^


728x90

이 글을 공유하기

댓글

Designed by JB FACTORY