Constant string lenght

Dark 21 Reputation points
2022-10-21T10:03:47.817+00:00

CSharp question:
If I declare constant string anywhere and then use it's string.Lenght in code - will it be replaced with an integer value during compilation?

Code Example:

public const string InfoToDataSeparator = "#&#";  
  
private string dynamicData = "Some data before separator#&#Some data after separator";  
public void Main()  
{  
    int index = dynamicData.IndexOf(InfoToDataSeparator);  
    if (index < 0)  
        throw new(nameof(dynamicData) + " has no required data sepator");  
      
    Console.WriteLine(dynamicData[(index + InfoToDataSeparator.Length)..]); // Length usage  
}  

(P.S: I know about string.Split(args) method. In source code, there is a reason why I using such thing)

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
9,461 questions
{count} votes

Accepted answer
  1. WayneAKing 4,521 Reputation points
    2022-10-21T10:48:59.767+00:00

    I'm interpreting your question to mean:

    When the string is const, is code that references the
    Length property of the string replaced with a
    hard-coded absolute value (the string length)
    at compile-time? Or does the compiler generate
    code that accesses the Length property at run-time,
    as it would for a non-const string?

    Using your example:

    public const string AnString = "An string value";  
      
    Console.WriteLine(AnString.Length > 5);  
      
    

    Does the compiler generate code that actually compares
    the Length property to 5, or does it generate code that
    literally uses the expression 15 > 5 because the length
    of the string is fixed and can not be changed at run time?

    Console.WriteLine(15 > 5);  
      
    

    Or does it generate code that skips a comparison altogether
    and just generates code that uses a true/false bool? e.g. -

    Console.WriteLine(true);  
      
    

    I haven't checked the Standard but I would expect that to
    be an implementation-specific detail (or feature).

    • Wayne

0 additional answers

Sort by: Most helpful