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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jun 6, 2021 (simplify).