views:

353

answers:

3
public class BaseFoo
{
    private string param;

    public BaseFoo(string param)
    {
        this.param = param;
    }
}

public sealed class SingletonFoo : BaseFoo
{
    static readonly SingletonFoo instance = new SingletonFoo();

    static SingletonFoo()
    {
    }

    public static SingletonFoo Instance
    {
        get
        {
            return instance;
        }
    }
}

Is this kind of inheritance possible, where the base class requires a constructor with parameters? (The above code won't obviously compile because no parameter is passed to the base class.)

If yes, how is it accomplished?

+1  A: 

You use the 'base' keyword:

public SingletonFoo (string param) : base(param)
{
}
Noon Silk
Ah, the ´static SingletonFoo()´ was preventing doing that. The purpose of the explicit static constructor is to force the compiler not to mark type as beforefieldinit, see http://www.yoda.arachsys.com/csharp/singleton.html . Will this modify how this works?
Well, I'm fairly sure any given singleton should be sealed anyway. But [I haven't tested], you should be able to put the 'base' statement on that constructor as well. Could be wrong though.
Noon Silk
@John: This is the correct approach, but only answers a portion of your question. You'd need to put this in an instance constructor, not the static constructor, and call it inline. I've put in an answer to demonstrate the entire process.
Reed Copsey
+1  A: 

I'm pretty sure a 'singleton' deriving from a non-singleton base class completely invalidates the entire concept of the pattern, which is often used inappropriately to start with.

Static constructors do not take parameters, so the only way to pass them to the base class would be via constructor-chaining but I'm pretty sure you can't invoke an instance constructor from a static constructor...

What exactly are you trying to do here?

jscharf
In .NET, technically, every singleton inherits from a non-singleton base class (System.Object). There is nothing fundamentally wrong with inheriting from a non-singleton type.
Reed Copsey
I'm aware of that but thanks. I'm just a little confused and skeptical as to why you'd want a singleton class derived from a non-static class, and if perhaps a global variable or regular static wouldn't be more appropriate.
jscharf
+2  A: 

You need to make an instance constructor, and then refer to it:

public sealed class SingletonFoo : BaseFoo
{
    static readonly SingletonFoo instance = new SingletonFoo("Some Value");

    static SingletonFoo()
    {
    }

    private SingletonFoo(string value) : base(value)
    {
    }
    // ...

This will let you declare the parameter in the inline constructor, and call it down the chain.

Reed Copsey