[C#] ref와 out ν‚€μ›Œλ“œ

2022. 5. 20. 22:50Β·πŸ“ Language/✏ C#

ref와 out ν‚€μ›Œλ“œ

ref와 out ν‚€μ›Œλ“œλŠ” 인자둜 λ„˜κΈ΄ λ³€μˆ˜λ₯Ό λ©”μ„œλ“œ λ‚΄λΆ€μ—μ„œ μ°Έμ‘° ν˜•νƒœλ‘œ μ‚¬μš©ν•œλ‹€λŠ” μ μ—μ„œ λ™μΌν•˜λ‹€.

  • 속성(Property)은 λ³€μˆ˜κ°€ μ•„λ‹ˆλ―€λ‘œ 전달할 수 μ—†λ‹€.

 

using System;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 0;
            foo(ref i);
            Console.WriteLine(i);

            int j;
            bar(out j);
            Console.WriteLine(j);
        }

        static void foo(ref int a)
        {
            a = 3;
        }

        static void bar(out int a)
        {
            a = 15;
        }
    }
}

// 3
// 15

 

κ·ΈλŸ¬λ‚˜ 두 ν‚€μ›Œλ“œλ„ 차이점은 μžˆλ‹€.

  • refλŠ” 인자둜 μ „λ‹¬ν•˜κΈ° 전에 λ°˜λ“œμ‹œ λ³€μˆ˜λ₯Ό μ΄ˆκΈ°ν™”λ₯Ό ν•΄μ•Ό ν•˜μ§€λ§Œ, out은 μ΄ˆκΈ°ν™”λ₯Ό ν•˜μ§€ μ•Šμ•„λ„ λœλ‹€.
  • out은 λ©”μ„œλ“œκ°€ λ°˜ν™˜λ˜κΈ° 전에 λ°˜λ“œμ‹œ 값을 ν• λ‹Ήν•΄μ•Ό ν•˜μ§€λ§Œ, refλŠ” 값을 λ³€κ²½ν•˜μ§€ μ•Šμ•„λ„ λœλ‹€.

 

즉, refλŠ” 인자둜 받은 λ³€μˆ˜λ₯Ό μˆ˜μ •ν•˜κ±°λ‚˜ 볡사 없이 μ‚¬μš©ν•  λ•Œ μœ μš©ν•˜κ³  out은 λ©”μ„œλ“œ μ•ˆμ—μ„œ λ§Œλ“€μ–΄μ§„ μ–΄λ–€ 값을 λ³€μˆ˜μ— λ„£μ–΄ λ°˜ν™˜ν•˜λŠ” 데 μ‚¬μš©ν•˜λ©΄ μœ μš©ν•˜λ‹€.

 

using System;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            // int i = 0;
            // 였λ₯˜ λ°œμƒ
            
            int i;
            foo(ref i);
            Console.WriteLine(i);

            int j;
            bar(out j);
            Console.WriteLine(j);
        }

        static void foo(ref int a)
        {
            a = 3;
        }

        static void bar(out int a)
        {
            // a = 15;
            // 였λ₯˜ λ°œμƒ
        }
    }
}
μ €μž‘μžν‘œμ‹œ (μƒˆμ°½μ—΄λ¦Ό)
'πŸ“ Language/✏ C#' μΉ΄ν…Œκ³ λ¦¬μ˜ λ‹€λ₯Έ κΈ€
  • [C# 6.0] μƒˆλ‘œμš΄ κΈ°λŠ₯ (1) - ν‘œν˜„μ‹ 레벨
  • [C#] Partial νƒ€μž…, Partial λ©”μ„œλ“œ
  • [C#] μΈλ±μ„œ(Indexer)
  • [C#] ν”„λ‘œνΌν‹°(Property)
Blxxming
Blxxming
CS 지식과 κ³΅λΆ€ν•˜λ‹€ 배운 것, κ²½ν—˜ν•œ 것 등을 κΈ°λ‘ν•˜λŠ” λΈ”λ‘œκ·Έμž…λ‹ˆλ‹€.
  • Blxxming
    πŸ’‘λ²ˆλœ©πŸ’‘
    Blxxming
  • 전체
    였늘
    μ–΄μ œ
  • 곡지사항

    • Tech Interview
    • πŸ“š Tech (246)
      • πŸ“ Computer Science (96)
        • ✏ OS (12)
        • ✏ Network & Web (10)
        • ✏ Database (11)
        • ✏ Data Structure (6)
        • ✏ Algorithm (40)
        • ✏ Design Pattern (9)
        • ✏ Cloud Computing (3)
        • ✏ (5)
      • πŸ“ Language (73)
        • ✏ Language (6)
        • ✏ C & C++ (11)
        • ✏ C# (19)
        • ✏ JAVA (37)
      • πŸ“ Game (43)
        • ✏ Computer Graphics (2)
        • ✏ Unity (14)
        • ✏ Unreal (26)
        • ✏ (1)
      • πŸ“ Book (34)
        • ✏ Effective (3)
        • ✏ Game Server (16)
        • ✏ Clean Code (14)
        • ✏ (1)
  • hELLOΒ· Designed Byμ •μƒμš°.v4.10.0
Blxxming
[C#] ref와 out ν‚€μ›Œλ“œ
μƒλ‹¨μœΌλ‘œ

ν‹°μŠ€ν† λ¦¬νˆ΄λ°”