Search code examples
c#.netstylecop

Static fields - string interpolation using static


public static class SomeRegexConsts
{
    public static readonly string FullName = $"{Name} {Surname}";

    private static readonly string Name = "[A-Z][a-z]+";

    private static readonly string Surname = "[A-Z][a-z]+";
}

In above example FullName will be equal to " " at runtime. It's related to the way static fields are initialized (from top to bottom).

In general I don't see any other solution than changing it to a getter:

public static string FullName => $"{Name} {Surname}";

Any ideas how to improve this code as I don't like this lambda, and moving FullName below Name and Surname is not an option as StyleCop won't let me do this.


Solution

  • If you don't want to move FullName below others, I think this's only solution for you.

    public static class SomeRegexConsts
    {
        static SomeRegexConsts(){
            FullName = $"{Name} {Surname}";
        }
    
        public static readonly string FullName;
    
        private static readonly string Name = "[A-Z][a-z]+";
    
        private static readonly string Surname = "[A-Z][a-z]+";