Reputation: 15
Hope you can help understand this, it seemed so natural to do this :
public interface IJob
{
bool started { get; set; }
}
public interface IJobManager
{
void StartJob(IJob job);
}
public class SomeJob : IJob
{
public bool started { get; set; }
public void OnlySomeJobDoesThis();
}
public class SomeJobManager : IJobManager
{
public void startJob(SomeJob job) { } // --> Error'SomeJobManager' does not implement interface member 'IJobManager.StartJob(IJob)'
}
But it won't compile, as you can see. I can't imagine why, .. as long as SomeJob implements the IJob interface the compiler should not really have to care ?
Upvotes: 0
Views: 164
Reputation: 3538
Your interface is saying "any class that implements me must implement a StartJob
method that can take any class that implements IJob."
Your implementation is saying "My StartJob method only works with a SomeJob, I don't know how to handle other implementations of IJob."
Your implementation is more restrictive than the interface, and therefore the compiler doesn't acknowledge that your implementation has fulfilled the interface requirements.
Upvotes: 3
Reputation: 62472
Imagine if you've got another class that implements IJob
:
public class FooJob : IJob
{
// Whatever...
}
And you create an instance of your SomeJobManager
like this:
IJobManager manager = new SomeJobManager();
Now, when you call StartJob
like this:
manager.StartJob(new FooJob());
What would you expect to happen? Your SomeJobManager
expects a SomeJob
instance, but the interface says that if must be an IJob
.
If your code was allowed you'd have broken the contract that the interface promises, which is that StartJob
can be called with anything that is an IJob
. You've said in your implementation that it has to be at least a SomeJob
, which isn't the same.
Upvotes: 5
Reputation: 3855
You are passing a concrete implementation of IJob
to the method but it wants an instance of IJob
.
Just do:
public class SomeJobManager : IJobManager
{
public void StartJob(IJob job) { }
}
Then just pass in SomeJob
when you call StartJob
:
//Something like this...
var myJob = new SomeJob();
manager.StartJob(myJob);
Upvotes: 2
Reputation: 69983
Two issues.
First, C# is case sensitive. You define the method as StartJob
(capital S), but implement startJob
(lowercase s).
Second, your method takes in SomeJob which implements IJob
. But your interface says the method should be able to take in an IJob
. That is, any class which implements the interface, which isn't limited to just SomeJob
.
Upvotes: 9