AyushISM
AyushISM

Reputation: 381

Static classes inheriting from abstract classes?

So I have a class A. It defines a lot of the behaviour (methods), but also leaves a lot to the subclasses to implement. This class is never going to have an instance. This is just going to define the behaviour that is common to all subclasses. The subclasses (A1, A2, A3, etc.) that are going to extend A are all going to be singletons. I don't want these subclasses to have multiple instances.

So the obvious way to do this would be create an abstract class A and then static classes A1, A2, A3 that extend A.

But apparently, this isn't allowed in C#. I'm assuming there is a good reason for this. People at Microsoft probably know a lot more about objected-oriented software design than I do. But I just need some help in figuring out why this design is "poor" and what would be an alternate better design.


I'm writing a RESTful API using WCF. There is a bunch of database tables that this service is going to perform CRUD operations on. There is a lot of code that is going to be common to all tables and a lot of code that is going to be specific to each table. Also, only one operation can be performed on the table at any given time.

So I thought I could have an abstract class TableHandler. And then multiple extensions of it such as TableAHandler, TableBHandler etc. Since I only want one instance of these subclasses, I wanted to make them static.

Upvotes: 2

Views: 4525

Answers (3)

Kędrzu
Kędrzu

Reputation: 2425

Simplest way to define singleton pattern is Lazy<T>:

public abstract class A { }

public class B : A
{
    private static Lazy<B> _instance = new Lazy<B>(() => new B());

    private B() { }

    public static B Instance
    {
        get
        {
            return _instance.Value;
        }
    }
}

This will also provide thread-safety to creation of your singleton.

Upvotes: -1

clcto
clcto

Reputation: 9648

Create a normal class that extends your base but follow the singleton pattern with a private constructor and static accessor to the instance.

abstract class A { }

class A1 : A
{
     private static A1 instance;
     public static A1 Instance
     {
         get
         {
             if( instance == null )
                 instance = new A1();
             return instance;
         }
     }

     private A1() { }
}

As noted by @ScottChamberlain, this implementation is not thread-safe. Using a static constructor will make the initialization thread-safe. More information can be found in this question: Is the C# static constructor thread safe?

Upvotes: 3

recursive
recursive

Reputation: 86084

Inheritance is something that affects objects. By definition, static classes do not allow instantiation. Therefore, they can't be involved in inheritance.

More practically, static methods can't be virtual, which pretty much eliminates any possible usefulness of being able to declare inherited static classes.

Upvotes: 5

Related Questions