Home
Search
C# Static StringUse static string fields to cache data and reduce string allocations.
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.
Static
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.
const
Readonly Readonly strings can be instance strings or static strings, and can only be assigned in a constructor.
Readonly
C# program that uses static, readonly, const strings
using System; using System.Diagnostics; class Program { readonly static string _test = DateTime.Now.ToString(); const string _label = "TIME: "; static void Main() { // Use readonly static string and const string. Console.WriteLine(_label + _test); } }
TIME: 3/23/2021 1:26:39 AM
Assignment. In this example program, we use a static string and assign it. A static string is initialized to null by having all its bits set to zero.
Null
Assign We assign static strings with the assignment operator. This is a bitwise copy of the reference value.
Note When you assign the value of ToString(), data is allocated on the managed heap. The reference now points to that object data.
ToString
C# 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); } }
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.
Home
© 2007-2021 sam allen. see site info on the changelog