Post

C++, C#) How to Pass Value Types by Reference

C++, C#) How to Pass Value Types by Reference

This post was migrated from Tistory. You can find the original here.

C# ref, out keywords

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System;

class Program
{
    static void Main()
    {
        int number = 5;
        MultiplyByTwo(ref number);
        
        int number2;
        MultiplyByTwo2(out number2);
    }

    static void MultiplyByTwo(ref int num)
    {
        num *= 2;
    }
    
    static void MultiplyByTwo2(out int num)
    {
        num *= 2;
    }
}

In C#, ref and out are keywords used to pass an argument by reference.

With ref, the variable must be initialized before the method call.

With out, the variable doesn’t need to be initialized before the call, but it must be assigned a value inside the method.

Both ref and out need to appear before the parameter in the method definition, and the keyword must also be used at the call site.

In C#, struct is a value type, and class is a reference type.

For example, if you pass a struct parameter without the out/ref keywords and change its value inside the method, the change is not reflected in main.

On the other hand, if you pass a class parameter without out/ref and change its value, the change is reflected in main as well.

Use out/ref when you want to pass a value type by reference.

Passing value types by reference in C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
static void testMethod(int& a) {
	a = 3;
}

static void testMethod(int* a) {
	*a = 4;
}

void main()  {
	int a = 5;
	testMethod(a);
    
   	int num = 5;
	int* ptr = #
	testMethod(ptr);
    
    return;
}

In C++, you use references or pointers.

Also, when passing parameters, both struct and class are passed by value by default. Even when passing a class, you still need to think in terms of references or pointers.

This post is licensed under CC BY-NC 4.0 by the author.