본문 바로가기
C#(CSharp)/기초강좌(Basic)

[11] C# 메소드 Method (Call by Value, Call by Reference, Output Parameter)

by swconsulting 2015. 2. 23.

C# 메소드는 Class에 선언한 함수입니다. 문법은 아래처럼 하면 됩니다.

<Access Specifier> <Return Type> <Method Name>(Parameter List)
{
   Method Body
}


<Example>

   public int FindMax(int num1, int num2)
   {
      int result;

      if (num1 > num2)
         result = num1;
      else
         result = num2;

      return result;
   }

위 메소드(Method)는 두개 값을 입력받아서 그중에 큰값을 찾아서 리턴하는 함수입니다.


세부적으로 설명하면 (public int FindMax(int num1, int num2))


-public으로 선언해서 모두 접근이 가능하다.

-int 로 선언해서 리턴형식을 지정했다.

-함수이름을 FindMax로 정의했다.

-마지막으로 2개 파라미터(num1, num2)를 입력 받는다.


[메소드에 파라미터 전달 방법]

-Value parameters(Call by value) : 입력한 값을 그대로 사용하고 source에는 변화를 주지 않습니다.

using System;

namespace CalculatorApplication
{
    class NumberManipulator
    {
        public void swap(int x, int y)
        {
            int temp;

            temp = x; 
            x = y;    
            y = temp; 
        }
    
        static void Main(string[] args)
        {
            NumberManipulator n = new NumberManipulator();

            int a = 100;
            int b = 200;

            Console.WriteLine("Before swap, value of a : {0}", a);
            Console.WriteLine("Before swap, value of b : {0}", b);

            n.swap(a, b);

            Console.WriteLine("After swap, value of a : {0}", a);
            Console.WriteLine("After swap, value of b : {0}", b); 
        }
    }
}
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200


-Reference Parameters(Call by reference) : 전달된 파라미터를 사용하고 이값이 함수 리턴되고 나서도 영향을 받습니다. 즉, Source 변수에 변경된 내용이 적용이 됩니다.


using System;
namespace CalculatorApplication
{
   class NumberManipulator
   {
      public void swap(ref int x, ref int y)
      {
         int temp;

         temp = x; 
         x = y;   
         y = temp; 
       }
   
      static void Main(string[] args)
      {
         NumberManipulator n = new NumberManipulator();

         int a = 100;
         int b = 200;

         Console.WriteLine("Before swap, value of a : {0}", a);
         Console.WriteLine("Before swap, value of b : {0}", b);

         n.swap(ref a, ref b);

         Console.WriteLine("After swap, value of a : {0}", a);
         Console.WriteLine("After swap, value of b : {0}", b);
 
         Console.ReadLine();
      }
   }
}
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100


swap(ref int x, ref int y) 함수를 호출한 후에 값이 변경되었습니다. 이 점이 Value Parameter와 가장 큰 다른점입니다.


-Output Parameters(Call by out) : 일반적으로 리턴을 1개 이상할 경우에 사용하는 방법입니다.

using System;

namespace CalculatorApplication
{
   class NumberManipulator
   {
      public void getValue(out int x )
      {
         int temp = 5;
         x = temp;
      }
   
      static void Main(string[] args)
      {
         NumberManipulator n = new NumberManipulator();
         int a = 100;
         
         Console.WriteLine("Before method call, value of a : {0}", a);         

         n.getValue(out a);

         Console.WriteLine("After method call, value of a : {0}", a);
         Console.ReadLine();

      }
   }
}
Before method call, value of a : 100
After method call, value of a : 5


위 샘플에서는 리턴값 대신  getValue(out int x ) 파라미터 x를 리턴 값으로 사용하는 것을 볼수 있다.   


이 글에서 설명한 call by value, call by reference는 혼동하기 쉽습니다, 혼동하지 말고 필요한 경우에 맞추어서 잘 나누어서 사용하기를 바랍니다.특히, collection(Array, List, Map)등을 파라미터로 넘길 경우에 주의해서 사용하기를 바랍니다.



참고 : http://www.tutorialspoint.com/csharp/index.htm