C# Deep Dive
Telerik Academy Alpha

 

 Table of contents

Stack vs Heap

 Stack

  • Keeps track what is executing or what's been called
     

  • Keeps everything in series of boxes one on top of the next
     

  • We can use only the top box content
     

  • When we are finished with the top box we throw it away
     

  • The stack is self-maintaining

 Heap

  • Keeps track of our objects
     

  • Holds information
     

  • Anything can be accessed at any time
     

  • The heap must be cleaned (Garbage Collector)

 Stack vs Heap

 Stack

 Heap

Garbage Collector

 Garbage collector

  • Unfortunately memory is not infinite
     

  • Manage it:

    • ​Manually

    • Automatically (Garbage Collector)

  • ​Manages the Heap memory

 Garbage collector

 Garbage Collector

  • Every object holds memory in the manged heap
     

  • The garbage collector is called periodically
     

  • If there are no direct or indirect references the GC frees the memory from the object
     

  • GC compacts the heap

Reference vs Value Types

 Value types

  • bool
  • byte
  • char
  • decimal
  • double
  • enum
  • float
  • int
  • long
  • sbyte
  • short
  • struct
  • uint
  • ulong
  • ushort
  • System.ValueType
public static void Main()
{
    int x = 5;
    int y = 30;

    bool isBigger = x > y;
}

 Value types

 Stack

public int ReturnValue()
{
    int x = 3;
    int y = x;
    y = 4;
    return x;
}

x | int = 3

y | int = 4

  • If we call the method it will return the value 3
     
  • These are all value types and are held in the Stack (not always)
    • ​In method declaration they are held in the Stack
       
    • If they are declared in a reference type they are held in the Heap

 Reference types

  • class
  • interface
  • delegate
  • object
  • string
  • System.Object
// The class is Reference type
public class Program
{
    static void Main()
    {
        // The list is Reference type
        List<int> list = new List<int>() { 1, 2, 3 };
        
        // The string is Reference type
        string a = "Pesho";
    }
}

 Reference types

public int ReturnValue()
{
    MyInt x = new MyInt();
    x.Value = 3;
    MyInt y = x;
    y.Value = 4;
    return x.Value;
}
  • If we call the method it will return the value 4
     
  • MyInt is a class (reference type​)
     
  • Reference types are always held in the Heap

 Stack

Heap

y | POINTER

x | POINTER

Myint

Value | int

Additional Materials

 Additional Materials

Questions?

[C#] Deep Dive

By telerikacademy

[C#] Deep Dive

  • 1,026