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:
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:
- classes
- fields
- methods
- properties
- operators
- events
- constructors
Stack-dynamic
In C#, value types are often but, not necessarily always, allocated on the stack. This includes (Cochran, 2006):
- bool
- byte
- char
- decimal
- double
- enum
- float
- int
- long
- sbyte
- short
- struct
- uint
- ulong
- ushort
Explicit heap-dynamic
Reference types are always allocated on the heap, which includes:
- class
- interface
- delegate
- object
- 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):
- it is part of a class
- it is boxed
- it is an array
- it is a static variable
- it is capture by a closure
- … 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
- Docs, M. (Ed.). (2015, July 20). static (C# Reference). Retrieved from https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/static
- 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/
- Gabe. (2010, December 20). Memory allocation: Stack vs Heap? Retrieved from https://stackoverflow.com/a/4487320