Search code examples
c#.netdatetimestring-interpolationc#-6.0

How to change property value that having new C# 6.0 string interpolation to new referenced value?


I have this class

public static class DateFormat
{
    public static string separator= "-";
    public static string DateFormat24H { get; set; } = $"yyyy{separator}MM/dd HH:mm:ss";
}

Now, when calling DateFormat24 hours it will print yyyy-MM/dd. now change the separator variable

DateFormat.separator = "/"; The DateFormat24H still the same yyyy-MM/dd

The string interpolation is assigned only in first initialization? So accessing the variable every time will use old string interpolation assigned? or am wrong. Or what I miss?


Solution

  • Firstly, your current code relies on the intalization order of your class, luckily it's the right order, but that is an implementation detail and may change

    Secondly, the following property, is an auto-implemented property, you can think of it just like setting it in the constructor, it's never re-evaluated again

    public static string DateFormat24H { get; set; } = $"yyyy{separator}MM/dd HH:mm:ss";
    

    Lastly, What you are most likely looking for is a expression body definition to implement a read-only property. Which would look like this.

    public static string DateFormat24H => $"yyyy{separator}MM/dd HH:mm:ss";
    

    Every time you call it, it will reevaluate the interpolation

    Update

    you see your Lastly, post. please can you gave full example of using get; set; both so evaluating the separator. and set the property. i mean using backing field or something like screenshot. prnt.sc/q22q0r Please execuse me about that.

    You can't do this with interpolation, you need to use String.Format Example of settable property

    private static string _separator = "/";
    
    private static string _backing = "yyyy{0}MM/dd HH:mm:ss";
    
    public static string DateFormat24H
    {
       get => string.Format(_backing, _separator);
       set => _backing = value;
    }
    

    Usage

    Console.WriteLine(DateFormat24H);
    _separator = "@";
    Console.WriteLine(DateFormat24H);
    DateFormat24H = "yyyyMM{0}dd";
    Console.WriteLine(DateFormat24H);
    

    Output

    yyyy/MM/dd HH:mm:ss
    yyyy@MM/dd HH:mm:ss
    yyyyMM@dd