43

I am trying to inherit a non-static class by a static class.

public class foo
{ }

public static class bar : foo
{ }

And I get:

Static class cannot derive from type. Static classes must derive from object.

How can I derive it from object?

The code is in C#.

tereško
  • 58,060
  • 25
  • 98
  • 150
Ali
  • 5,286
  • 9
  • 33
  • 36

16 Answers16

59

There's no value in deriving static classes. The reasons to use inheritance are:

  • Polymorphism
  • Code reuse

You can't get polymorphism with static classes, obviously, because there is no instance to dynamically dispatch on (in other words, it's not like you can pass a Bar to a function expecting a Foo, since you don't have a Bar).

Code reuse is easily solved using composition: give Bar a static instance of Foo.

munificent
  • 11,946
  • 2
  • 38
  • 55
  • 3
    +1 For providing a simple and appropriate solution to the OP's problem. – Brian Dec 30 '10 at 21:05
  • Sorry for "thread digging" but I'm wanting to do the same thing and while I think your answer is a good one, I'm wondering how you would approach the use case where `foo` has some protected methods that `bar` would like to use. – Samo Mar 09 '11 at 18:41
  • 2
    You're saying you want a *static* `Bar` class that inherits from a *non-static* `Foo` so that it can get to its protected members? There's a lot of fishiness in that design (it's rare for a single class to make sense in both a static and non-static context). But, assuming you have a valid reason for this, one solution is to have `Bar` have a private inner non-static class that inherits from `Foo` (call it `FooWrapper`). It has public methods that forward to the protected ones it inherits. `Bar` can then have an instance of `FooHelper` and get to the protected members in `Foo` through that. – munificent Mar 10 '11 at 00:51
  • 1
    you could use the singleton pattern to have inheritance and static(ish) behaviour – BritishDeveloper Mar 17 '11 at 15:19
  • Another use for deriving is to provide default arguments for Generic parameters. As illustrated in this question, C# does not support defaults but you can get around that by overriding. http://stackoverflow.com/questions/2747874/default-for-generic-type public static class ActionInvoker : ActionInvoker { } public static class ActionInvoker { } – TamaMcGlinn May 02 '16 at 09:56
  • Let's discuss "There's no value in deriving static classes": I'm not objecting that allowing deriving static classes could create some consistency issues in the language, still people are asking for it. Let's consider one of the best use of static classes, which are extension methods: it's not possible to compose classes with extension methods which would help to deal with ambiguities, requiring less namespace qualification and, in the end, better reuse the code. If it doesn't break the language in other ways, that would be an interesting use for static class inheritance. – ceztko Dec 04 '20 at 18:49
24

From the C# 3.0 specification, section 10.1.1.3:

A static class may not include a class-base specification (§10.1.4) and cannot explicitly specify a base class or a list of implemented interfaces. A static class implicitly inherits from type object.

In other words, you can't do this.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
19

The error message is bogus. It's not saying "an" object. It's talking about the built-in type called "object" which is the base of everything in .NET.

It should say "static classes can not specify a base type".

GeekyMonkey
  • 12,478
  • 6
  • 33
  • 39
  • 5
    No, it should say "Static classes cannot specify a base type. Static classes always implicitly derive from System.Object." Note that you can't derive one static class from another static class either. – Jon Skeet Feb 17 '09 at 10:29
9

Taken from http://msdn.microsoft.com/en-us/library/79b3xss3(VS.80).aspx

The main features of a static class are:

They only contain static members.

They cannot be instantiated.

They are sealed.

They cannot contain Instance Constructors (C# Programming Guide).

So, inheriting from a non-static class violates the first feature of static classes on this list by introducing non-static members to your static class.

Chris McAtackney
  • 5,192
  • 8
  • 45
  • 69
  • 1
    This is the answer that addresses the root issue. – Anshul Jul 31 '13 at 14:33
  • It's a shame they don't allow you to inherit from a static class really, as I've just come across a scenario where it would have been handy. If it were to be implemented, you'd simply provide a static parameterless constructor to call the constructor of the base class, and all of the instance members would become static members... – Lee.J.Baxter Jun 29 '17 at 12:56
2

I don't think C# supports inheritance for static classes.

One option would be to use the singleton pattern instead

public class foo
{ }

public class bar : foo
{
    private bar instance;
    public bar GetInstance()
    {
        if(instance == null) instance = new bar();
        return instance;
    }

    private bar(){} //make default constructor private to prevent instantiation 
}
RSlaughter
  • 1,191
  • 3
  • 11
  • 23
  • Singleton isn't something I'd recommend. Be very careful about using it. See: http://www.google.com/search?source=ig&hl=en&rlz=&=&q=singleton+bad&btnG=Google+Search&aq=f – Matthew Olenik Feb 17 '09 at 10:34
  • 2
    I think your example is flawed, if two threads succeed passing the if(instance == null) it will instantiate a new bar two times. – TomHastjarjanto Feb 17 '09 at 10:34
  • The above code generates error : Static classes cannot have instance constructors – Ali Feb 17 '09 at 10:38
  • 2
    Edited to remove static declaration on bar class. I didn't say it was thread safe, presumably you could put a lock on checking / creation of the instance. Personally I think singletons are going the way of goto, people assume they're always evil, which isn't always the case. DI can be overkill too – RSlaughter Feb 17 '09 at 11:00
  • Considering that it no longer even has any static classes, your answer is a bit far off from what the OP is trying to do. Also note that any threading issues that exist within munificent's solution would also exist if the OP was able to have a static class derive from a class. – Brian Dec 30 '10 at 21:04
2

For everyone finding this question many years later, you might be able to do what you are hoping. There are a few scenarios where this really helps and makes sense - but it doesn't actually have anything to do with inheritance.

It is actually quite straightforward:

using static MyNamespace.MyStaticClassIWantToPretendIsABaseClass;

namespace MyNamespace
{
     static class IncludesBase
     {
          // Access static class that you are pretending is a base class
     }
}

By playing around with this, you can make your code better or worse. This can be really useful, but thinking about it as a base class is incorrect.

Mark D
  • 3,317
  • 1
  • 26
  • 27
1

As Christopher have pointed out, suppose we can derive static class from non-static class.

for example:

public class foo
{
    public int myVar;
}

public static class bar : foo { }

here, bar class derived from foo, hence static class Bar has non-static member myVar now, and According to the c# Specification , Static Class can not contains non-static members!

Ayub
  • 2,345
  • 27
  • 29
1

Like stated earlier the C# spec say this can't be done. You can't implement a interface with static classes either. Your best bet is to change from using a static class to using a class that uses the singleton pattern. You will have only one instance (similar to how the static class works) and you will be able to inherit behavior or implement interfaces.

You read up on Singletons here, here, and here.

RS Conley
  • 7,196
  • 1
  • 20
  • 37
0

Doesn't all classes (static included) already derive from object? As in, by default?

Also, like it says, "Static class cannot derive from type.", so I don't think what you are doing is possible. Why would you want a static class to derive from a type anyways?

Svish
  • 152,914
  • 173
  • 462
  • 620
0

It can't. You have to create a normal class to derive from some other class.

Grzenio
  • 35,875
  • 47
  • 158
  • 240
0

All classes derive implicitly from Object. That said, although static classes (which by definition are just containers for static members) "derive" from object, there is nothing you can get from that fact.

Anton Gogolev
  • 113,561
  • 39
  • 200
  • 288
0

The error message is misleading.

bar can't inherit from foo because foo can be instantiated and bar can't.

teedyay
  • 23,293
  • 19
  • 66
  • 73
0

If you're trying to stop people creating instances of the class, just add a private default constructor.

Mark Rendle
  • 9,274
  • 1
  • 32
  • 58
  • My aim is to stop making instances of bar but the problem with private constructor would be that I would need to change variables and function in foo also to static to be able to access them. – Ali Feb 17 '09 at 15:42
  • In that case you should be using composition instead of inheritance; bar contains a static readonly instance of foo. – Mark Rendle Feb 18 '09 at 12:41
0

static class can not be base class for other classes and it can not be extended.

static class can be inherited only from "object" class(.net base class).

Additional information: All classes in .net inherited from "object" class, even any static class also.

The difference is even though static class inherit "object class" it inherit only two static methods from "object" class.

Other non-static classes inherit other four methods.

Syed
  • 953
  • 1
  • 8
  • 11
0

The OP asked "How can I drive it from object?". The object here is not an instance of another class so the answer is you don't. The object refers to the System.Object base class which is the default base class for all types in .NET. The error message is bit misleading.

Just for completeness, on the flip side, a static class also cannot be inherited or extended because it is both an abstract and a sealed class.

Stack Undefined
  • 1,050
  • 1
  • 14
  • 23
0

As said in other answer, the compiler message is confusing but correct. You can write:

static class A : object
{
}

of course it is not really useful to explicitly state this inheritance but the inheritance itself is actually useful in the framework as you override the object's virtual members:

    static class A : object
    {
        public static new string ToString()
        {
            return "I am object A";
        }

        public static new int GetHashCode()
        {
            return ToString().GetHashCode();
        }
    }
Julien
  • 353
  • 3
  • 11