Skip to content

Instantly share code, notes, and snippets.

@maacpiash
Created July 20, 2018 12:13
Show Gist options
  • Save maacpiash/48dc6d3bfb99c2b4c2110f76ad7b5f59 to your computer and use it in GitHub Desktop.
Save maacpiash/48dc6d3bfb99c2b4c2110f76ad7b5f59 to your computer and use it in GitHub Desktop.
Testing different types of pass-by/return types: value vs reference
using System;
using static System.Console;
namespace RefTest
{
class Program
{
static void Main(string[] args)
{
ValVal(); // Returns value, pass by value
RefVal(); // Returns reference, pass by value
ValRef(); // Returns value, pass by reference
RefRef(); // Returns reference, pass by reference
}
static void ValVal()
{
int[] list = {1, 2, 3, 4, 5};
var one = ValVal(list);
one = 6;
WriteLine($"Val-Val: {list[0]}"); // output = 1
}
static void RefVal()
{
int[] list = {1, 2, 3, 4, 5};
ref var one = ref RefVal(list);
one = 6;
WriteLine($"Ref-Val: {list[0]}"); // output = 6
}
static void ValRef()
{
int[] list = {1, 2, 3, 4, 5};
var one = ValRef(ref list);
one = 6;
WriteLine($"Val-Ref: {list[0]}"); // output = 1
}
static void RefRef()
{
int[] list = {1, 2, 3, 4, 5};
ref var one = ref RefRef(ref list);
one = 6;
WriteLine($"Ref-Ref: {list[0]}"); // output = 6
}
static int ValVal(int[] numbers) => numbers?[0] ?? 0;
static ref int RefVal(int[] numbers) => ref numbers[0];
static ref int RefRef(ref int[] numbers) => ref numbers[0];
static int ValRef(ref int[] numbers) => numbers?[0] ?? 0;
}
}
/*
Conclusion: value is accessible for modification when a reference is returned.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment