Search code examples
c#backcolor

Changing the BackColor of a Windows Form


Why can't I change the backcolor of my form this way?

MainForm.BackColor = System.Drawing.Color.Black;

This is what I get in the console:

An object reference is required for the non-static field, method, or property 'System.Windows.Forms.Control.BackColor.get' (CS0120) 

Solution

  • Static Classes are classes that cannot be instantiated. Static classes have static methods or static properties (or both). When you use a line like this:

    MainForm.BackColor = System.Drawing.Color.Black; // <class name>.<property>
    

    What the C# compiler does first is look for a local class variable called MainForm. Since there was none, it then looked outside your local scope and found your Windows.Form class called MainForm.

    It then looked to see if the class MainForm has a static property called BackColor. The compiler then said "Oh look, there is a property called BackColor, but its not static", which is when the compiler complained and threw you the error you experienced.

    By changing it to this.BackColor, the compiler knew you wanted to set the background color OF THIS INSTANCE of MainForm, which was this or, by default, form1:

    this.BackColor = System.Drawing.Color.Black; // <this instance>.<property>
    

    And as a side note, the keyword this is not required. Omitting it assumes "this object". You can do this just as well:

    BackColor = System.Drawing.Color.Black; // <this instance>.<property>
    

    Hope this makes more sense!