Static string. A static string is stored in one location. It has many differences from regular strings, such as instance strings and local variables.
Static keyword. The term "static" means a field is not created when a class is created with "new." The string is tied to the type declaration rather than the object instance.
An example. In this first example we use a static readonly string and a const string. Const strings can be accessed with the same syntax as static strings.
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);
}
}String is null
--- Value, Main method ---
1000
--- Value, Read method ---
1000
Program notes. Static and instance strings can be used in other methods on the same type. Static strings can be used by all instance and static methods on the type.
A discussion. We discuss differences between static strings and readonly and const strings. Static strings can be assigned as many times as you want in your program.
And This is different from const strings, which must be assigned to a constant value.
Keyword notes. Static can be applied to various things in C#. It does not affect the usage of the type. Static things just exist only once, regardless of the number of instances.
A summary. Static strings can be used in C# programs. We described static string usage and how "static" points to only one storage location in a program.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 6, 2021 (simplify).