Search code examples
c#winforms

Non-constant fields generate CA2211 warning, but I need to assign this variable


In my WinForms project I have a string declared thus:

public partial class MainWindow : Form
{
    public static string MyTitle;
    // more code here
    
    public MainWindow()
    {
        MyTitle = Text;
        // etc
    }
}

Now I can refer to it in another class like MainWindow.MyTitle

By doing it like this I get a warning

`CA2211: Non-constant fields should not be visible`

But I cannot declare it const or readonly since I need to assign it in the constructor.

What is the proper way to deal with this situation.

I tried changing it by removing the static phrase from the declaration but then I get another error CS0120 An object reference is required for the non-static field, method, or property


Solution

  • If it's a static field, it should be either initialized directly at declaration or in a static constructor.

    Initializing a static field in an instance constructor is a conceptual mistake, since static members belong to the type itself and not to any particular instance of that type.

    Consider the following wrong code:

    class C
    {
        public static string Name;
        public C(string name) => Name = name;
    }
    

    and using this class:

    var c0 = new C("Zohar"); 
    Console.WriteLine(C.Name); // output "Zohar"
    var c1 = new C("Peled");
    Console.WriteLine(C.Name); // output "Peled"
    

    There are valid examples where you want to change the value of a static member from a non-static method or constructor, however. Imagine for example a class that needs to report how many instances of itself have been created:

    class C
    {
        public static int NumberOfInstances {get;private set;} 
        public C()
        {
            NumberOfInstances++;
        }
    
    }