In the C# programming language. Static strings have many differences with regular strings, such as instance strings and local variables. They are tied to the type declaration rather than the object instance. Here we look at an example of using static strings in a C# program, and then discuss some of their advantages and compare them to other kinds of strings.
When you use the static keyword on a string, you indicate that you only need one string reference, which can point to only one object at a time. If you have many string values in your program, don't choose the static keyword.
using System;
class Program
{
static string_examples;
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);
}
}
Out Put:
String is null
--- Value, Main method ---
1000
--- Value, Read method ---
1000
Initial value of static string. The static string _example here is initialized to null by having all its bits set to zero.
Assigning static string. You can assign static strings such as _example using the assignment operator. The assignment always performs a bitwise copy of the reference value. When you assign the value of ToString() in the example.
Using static string in another method. Static and instance strings can be used in other methods on the same type.
The static keyword can be applied to invocable members in the C# programming language. It can also be applied to the class keyword, but not the namespace keyword. However, a static member variable such as a static string is still a field, while a static method is a function type.