C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Info: The static keyword in the C# language was not chosen for its meaning. It was instead chosen because it was used in C++ and C.
Info: The static string is initialized to null by having all its bits set to zero. We check the value of the static string before it is assigned.
NullAssign: We assign static strings with the assignment operator. This is a bitwise copy of the reference value.
Assign VariablesNote: When you assign the value of ToString(), data is allocated on the managed heap. The reference now points to that object data.
ToStringC# program that uses static string
using System;
class Program
{
static string _example;
static void Main()
{
//
// Check initial value of static string.
//
if (_example == null)
{
Console.WriteLine("String is null");
}
//
// Assign static string to value.
//
_example = 1000.ToString();
//
// Display value of string.
//
Console.WriteLine("--- Value, Main method ---");
Console.WriteLine(_example);
//
// Call this method.
//
Read();
}
static void Read()
{
//
// Display value of string.
//
Console.WriteLine("--- Value, Read method ---");
Console.WriteLine(_example);
}
}
Output
String is null
--- Value, Main method ---
1000
--- Value, Read method ---
1000
And: If it was to change the value of the reference, the static string would also be changed in Main.
Tip: The static keyword does not affect the usage of the type, only that it exists only once, regardless of the number of instances.
Singleton, Static Class