티스토리 뷰

일을 시작한지 1년쯤 되었을 때인가.. 나한테 이것에 관해 질문한 신입사원이 있었다.

그때는 나도 사원이었기에 여차저차 내가 경험한 대로 설명을 했던 것 같은데 오늘에서야 글로 정리해본다. 

Call by value vs  Call by reference

처음 프로그래밍을 접하면, 헷갈리기 쉬운 내용이다. 

먼저, 설명할 내용을 요약하자면, Call by value와 Call by reference는 함수 호출 방식에 따른 구분이고, 

우리가 사용하는 변수는 Value type variable(int, string 등) 과 Reference type variable(객체)로 구분된다. 

참조 타입 변수의 경우, 변수를 새롭게 set하지 않고, 그 안에 내용만 변경하는 경우에는 Call by value 방식으로도 내가 원하는 결과값을 얻을 수 있다.

즉, 내가 전달 할 인자의 특성을 알고 함수를 작성하면 좀더 명확한 프로그래밍을 할 수 있다. 

 

  • Call by value : 값에 의한 호출 
  • Call by reference : 참조에 의한 호출 

Integer 변수

Call by value vs  Call by reference

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Hello_World
{
    class Program
    {
        static void Main(string[] args)
        {
            int age = 28;

            ChangeValue(age);
            Console.WriteLine($"My age is {age}."); // My age is 28.

            ChangeReferenceValue(ref age);
            Console.WriteLine($"My age is {age}."); // My age is 18.
        }

        private static void ChangeValue(int num)
        {
            num = num - 10;
        }

        private static void ChangeReferenceValue(ref int num)
        {
            num = num - 10;
        }
    }
}

Call By Reference를 활용하면 나이도 어려질 수 있다. 

 

string 변수

Call by value vs  Call by reference

class Program
    {
        static void Main(string[] args)
        {
            string lastName = "KIM";

            ChangeLastName(lastName);
            Console.WriteLine($"My last name is {lastName}."); // My last name is KIM.

            ChangeReferenceLastName(ref lastName);
            Console.WriteLine($"My last name is {lastName}."); // My last name is LEE.
        }

        private static void ChangeLastName(string lastName)
        {
            lastName = "LEE";
        }
        
        private static void ChangeReferenceLastName(ref string lastName)
        {
            lastName = "LEE";
        }
    }
}

Call By Reference를 활용하면 성도 바꿀 수 있다. 

 

참조 타입 변수

Call by value

public class Person
{
    public string LastName { get; set; } = string.Empty;
    public int Age { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var person = new Person() {LastName = "KIM", Age = 28 };

        ChangePersonAge(person);
        Console.WriteLine($"My age is {person.Age}."); // My age is 18.

        ChangePersonLastName(person);
        Console.WriteLine($"My last name is {person.LastName}."); // My last name is LEE.
    }

    public static void ChangePersonAge(Person person)
    {
        person.Age = person.Age - 10;
    }

    public static void ChangePersonLastName(Person person)
    {
        person.LastName = "LEE";
    }
}

객체를 사용하면, Call By Value로도 나이와 성을 바꿀 수 있다. Call By Reference로도 당연히 바꿀수 있겠지만, 굳이 그렇게 할 필요가 있을까 싶다.

'Computer Engineering > C#(.Net)' 카테고리의 다른 글

[C#] string 과 StringBuilder  (0) 2022.04.13
[C#] VScode에서 C# 콘솔 어플리케이션 만들기  (0) 2022.04.05
WPF / Dependency Property  (0) 2022.03.29
Prism과 실습  (0) 2021.09.28
.NET 프레임워크  (0) 2021.09.27