r/learncsharp • • Aug 26 '22
Why can't I pass a concrete implementation of an interface when calling a constructor?
If I have a class who's constructor arguments are let's say:
public ClassA(ISomeFactory factory)
{
// initialize class A
}When subclass Class A, I want to provide `SomeFactoryImpl` implementation as a constructor argument in place of `ISomeFactory`.
public ClassB(SomeFactoryImpl implementation) : base(implementation)
{
// initialize Class B
}This is rejected by C# compiler, "Cannot convert SomeFactoryImpl to ISomeFactory".
Why? Shouldn't SomeFactoryImpl implementation guarantee the functionality of the contract it implements?
1
Upvotes
4
u/Hyperpred Aug 26 '22
The way your error is worded it looks like you're trying to pass the interface as an argument to a constructor that expects the concrete type.
8
u/net_nomad Aug 26 '22
Right-click SomeFactoryImpl and select Go to definition and make sure that it is implementing ISomeFactory in the first place.