21

I am having a problem in C#, the output states:

Error   1   Static class 'WindowsFormsApplication1.Hello2' 
cannot derive from type 'System.Windows.Forms.Form'. Static classes 
must derive from object.

How could I correct this?

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {
             Hello2.calculate();
        }
    }



    public class Hello : Form
    {
        public string test { get; set; }

    }


    public static class Hello2 : Form
    {
        public static void calculate()
        {
            Process.Start("test.exe");

        }
    }
kprobst
  • 16,165
  • 5
  • 32
  • 53
Matt
  • 231
  • 2
  • 3
  • 5
  • 4
    Why are you trying to create a static class that derives from Form? – Tim Jun 27 '11 at 17:46
  • @Tim You say that as if it's unheard of. I've come across several examples right here on SO of folks trying to achieve this functionality (which, by design, is possible in Java,) by relying on singletons when using C#. – arkon Jul 09 '15 at 18:58
  • @b1nary.atr0phy - I never said it was unheard of or even meant to imply it. I was simply asking OP why they were trying to do that. – Tim Jul 09 '15 at 19:08
  • look at this similar question: [Why can't I inherit static classes?](https://stackoverflow.com/q/774181/791745) – Navid Rahmani Jun 27 '11 at 17:50

2 Answers2

46

It means that static classes can't have : BaseClass in the declaration. They can't inherit from anything. (The inheritance from System.Object is implicit by declaring nothing.)

A static class can only have static members. Only instance members are inherited, so inheritance is useless for static classes. All you have to do is remove : Form.

Joel B Fant
  • 24,406
  • 4
  • 66
  • 67
  • Maybe it would be better to instantiate an instance of **Base-Class** as a property/field of **Derived-Class**, Then expose whatever functionality (that you like) out of it. – Rzassar Sep 14 '16 at 04:04
  • 1
    I fell into this one: basically I was declaring inner classes `static` as a habit from Java programming, where there is a distinction between static and non-static inner classes that does not exist in C#. Solution: just drop the "static" keyword. – Michael Kay Jan 29 '21 at 09:32
1

Is there some reason to derive Hello and Hello2 from Form? If not, just do:

public static class Hello2
{
    ...
}

likewise for class Hello

The Evil Greebo
  • 7,013
  • 3
  • 28
  • 55