repl.it
@kironroy/

ref_vs_value

C#

Reference Types and Value Types

fork
loading
Files
  • main.cs
  • main.exe
  • notes.txt
main.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using System;

class MainClass {
  /*
  When you copy a value type from a different variable, a copy
  of that value is taken and stored in the target value.  That is why they are called value types.  Their values are copied.

  In memory (stack), making a change to one variable DOES effect the other variable
  */
  
  public static void Main (string[] args) {
    
    // ints are primitive type (structure, Value)
    var a = 12;  
    var b = a;

    b++;

    Console.WriteLine("Value types below");
    Console.WriteLine(string.Format("a: {0}, b: {1}", a, b));

    Console.WriteLine("-------------------");

    // arrays are class type (classes, Reference)
    
    var arrayOne = new int[3] {2, 4 ,6};
    var arrayTwo = arrayOne;
    arrayTwo[0] = 0;
    var arrayThree = arrayTwo;

    
    Console.WriteLine("Reference types below");
    Console.WriteLine(string.Format("arrayOne: {0}, arrayTwo: {1}", arrayOne[0], arrayTwo[0]));
    Console.WriteLine(arrayThree[0]);
    
    /*

    Create and intialize a an array, it is in the Heap with a memory location (the actual array).  
    
    Next the runtime (CLR) creates a variable on the stack identifed as arrayOne (meomroy address). The value inside this variable/memory location is a memory address of the object in the Heap (the actual array)  arrayOne points to the actual adddress in the Heap.  

    Making a change to arrayOne or arrayTwo refrence the same memory address, so the changes will take place in both arrays!

    Runtime

    */

    




    
  }
}