2

I have partial classes with static readonly fields, and in one of the partial classes I'm creating a static readonly list of all the static readonly members. For some reason, the list ends up with the correct numbers of entries, but all the entries all null.

public partial class Numbers
{
    public static readonly List<string> All = new List<string>
    {
        One,
        Two
    };
}

public partial class Numbers
{
    public static readonly string One = "One";
}

public partial class Numbers
{
    public static readonly string Two = "Two";
}

var all = Numbers.All;

// all.Count() is 2
// all.First() is null
// all.Last() is null

Can anyone help me understand why this is?

I've noticed that if I change the Numbers.All field to be a non-readonly property, the values within the list are as expected, not null. So I'm guessing this is something to do with how the partial classes are read, or something to do with the readonly usage, but I'm really thrown by this.

Switching to a non-readonly property is obviously easily done, and maybe that's a better approach(?), but I'm really curious why using readonly fields doesnt work.

4
  • 1
    Does this answer your question? Initialization Order of Static Fields in Static Class Note by the way, your problem is nothing directly to do with readonly Commented Mar 13, 2021 at 22:20
  • @Charlieface Yes, I think this explains the issue I'm seeing. So what I'm taking away from this is, use a static constructor to ensure the static members are initialised before the constructor is executed. Commented Mar 13, 2021 at 22:27
  • 1
    Indeed, a static constructor is the solution.. Commented Mar 13, 2021 at 22:28
  • @Orace Yes that's really helpful, I didnt realise that using partial classes would have such an impact. Thanks Commented Mar 13, 2021 at 22:28

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.