1

I have a class that takes an interface as one of the arguments to it's constructor. Is there a way to create an instance of a specific implementation that I can use as a default value for a parameter?

    interface IClassA
    {
        void AMethod();
    }

    class ClassA : IClassA
    {
        void AMethod()
    {
        // Do stuff
    }
}

class Other
{
    public Other(IClassA ia = new ClassA())
    {
    }
}

The compiler error I get for this, and everything else I have tried is "Default parameter value for 'ia' must be a compile-time constant"

this is easily doable in c++ (I'm relatively inexperienced in c#)

How do I make an instance of a class be a compile-time constant?

Engin Ears
  • 21
  • 3
  • Does it always have to be same instance (as your title suggests, at least to me) or every time new one, when the constructor is called (as your code suggests)? – sticky bit May 03 '19 at 22:04
  • You can also add a constructor with no parameter that calls the other constructor with the default, like so: `public Other() : this(new ClassA()) {}`. – Jonathon Chase May 03 '19 at 22:09
  • @sticky bit. In the context of this question, yes. It is more of a 'is this possible' type question. I can conceive of a situation where I might want a specific default instance. In c++ I would do this by instantiating an extern static instance in another translation unit, that I could then use as a default instance. I'm just curious if such is possible in C#. – Engin Ears May 05 '19 at 16:29

1 Answers1

1

You can specify null as the default value, and then coalesce with an actual value:

public Other(IClassA ia = null)
{
     ia = ia ?? new ClassA();
     ia.AMethod();
}

Passing null new Other(null) or nothing at all new Other will use new ClassA() as "default" value.

Xiaoy312
  • 14,292
  • 1
  • 32
  • 44
  • Yeah, I thought of this as a workaround, but I was wondering if there was a way I could declare an instance of ClassA to serve as the default value for the arg. Easy to do in c++. Just surprised such a simple thing might not be possible in c#. Thanks. – Engin Ears May 03 '19 at 22:07
  • @EnginEars "simple thing" - it is always good idea to try to design feature you like and see how simple it is. I.e. in this case think about how static initialization that calls such method will interact with constructors... – Alexei Levenkov May 03 '19 at 22:12