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#.
The solution couldn't be simpler: public class A { public const string ConstantA = "constant_a"; public const string ConstantB = "constant_b"; // ... } public class B : A { public const string ConstantC = "constant_c"; public const string ConstantD= "constant_d"; // ... }
A static class can only contain static data members, static methods, and a static constructor.It is not allowed to create objects of the static class. Static classes are sealed, means you cannot inherit a static class from another class.
No, It's not possible to inherit Static class. Static classes are sealed classes so we can't inherit that.
Remember: In static class, we can easily create objects. The following are major differences between static nested classes and inner classes. A static nested class may be instantiated without instantiating its outer class. Inner classes can access both static and non-static members of the outer class.
There's no value in deriving static classes. The reasons to use inheritance are:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With