C# - TPL2141 logo C# - TPL2141

Storage binding defines when a variable is bound to a memory cell and for how long it remains bounded. C# only has 3 binding categories:

  1. static
  2. stack-dynamic
  3. explicit heap-dynamic

Static

In C#, local variables cannot be defined as static.

void Main()
{
  // ERROR: The modifier "static" is not valid for this item
  static int age = 123;
}

Instead, the static keyword has another meaning: it is used to declare a static member, which belongs to the type itself rather than to a specific instance of the class (Docs, 2015).

public class Person
{
  // static class member
  public static int Age = 123;
}
void Main()
{
  Console.WriteLine($"Age: {Person.Age}");
}

Output:

Age: 123

It can only be used on:

  1. classes
  2. fields
  3. methods
  4. properties
  5. operators
  6. events
  7. constructors

Stack-dynamic

In C#, value types are often but, not necessarily always, allocated on the stack. This includes (Cochran, 2006):

  1. bool
  2. byte
  3. char
  4. decimal
  5. double
  6. enum
  7. float
  8. int
  9. long
  10. sbyte
  11. short
  12. struct
  13. uint
  14. ulong
  15. ushort

Explicit heap-dynamic

Reference types are always allocated on the heap, which includes:

  1. class
  2. interface
  3. delegate
  4. object
  5. string

The heap is managed by Garbage Collector (GC), which will find all objects in the heap that are not being accessed and delete them. Note that a value type will be allocated on the heap when (Gabe, 2010):

  1. it is part of a class
  2. it is boxed
  3. it is an array
  4. it is a static variable
  5. it is capture by a closure
  6. … etc

Example

Adapted from (Cochran, 2006)

public class MyInt
{
  public int MyValue;
}
void Main()
{
  // on stack
  int value = 123;
  
  // on heap, but the reference/pointer to the object is on the stack
  MyInt result = new MyInt();
  
  // on heap, because MyValue is part of a class (which is a reference type)
  result.MyValue = value + 200;
}

When the variables go out of scope, they are popped from the stack.

The object on the heap will eventually be collected by Garbage Collection.

References

  1. Docs, M. (Ed.). (2015, July 20). static (C# Reference). Retrieved from https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/static
  2. Cochran, M. (2006, January 14). C# Heap(ing) Vs Stack(ing) in .NET: Part I. Retrieved from https://www.c-sharpcorner.com/article/C-Sharp-heaping-vs-stacking-in-net-part-i/
  3. Gabe. (2010, December 20). Memory allocation: Stack vs Heap? Retrieved from https://stackoverflow.com/a/4487320