Reputation: 2966
I have been trying to learn dependency injection but I have 2 errors when I run my code:
DependencyInjection.Message.Sms()
must declare a body because it is not marked abstract, extern, or partial.DependencyInjection.IInterface
to DependencyInjection.MyClass
. An explicit conversion exists (are you missing a cast?)Is the code below a good design for DI?
namespace DependencyInjection
{
public interface IInterface
{
}
public abstract class Message
{
public virtual void Sms();
}
public class MyClass : Message, IInterface
{
public override void Sms()
{
Console.WriteLine("Sms gönder.");
}
}
public class ClassManager
{
private IInterface _myinterface;
public MyClass Xyz
{
get { return _myinterface; }
set { _myinterface = value; }
}
public ClassManager(IInterface myinterface)
{
_myinterface = myinterface;
}
}
}
Upvotes: 1
Views: 2224
Reputation: 13872
1) DependencyInjection.Message.Sms()' must declare a body because it is not marked abstract, extern, or partial
Add abstract
keyword (and remove virtual) to method declaration:
public abstract void Sms();
2) Cannot implicitly convert type 'DependencyInjection.IInterface' to 'DependencyInjection.MyClass'. An explicit conversion exists (are you missing a cast?)
private IInterface _myinterface;
public MyClass Xyz
{
get { return _myinterface; }
set { _myinterface = value; }
}
Xyz
has return-type of type MyClass
but in get
you are returning _myinterface
which is of type IInterface
.
Change to following:
public IInterface Xyz
{
get { return _myinterface; }
set { _myinterface = value; }
}
Upvotes: 4
Reputation: 25201
You're declaring a virtual method with no body. Virtual methods must declare a body that will act as the default implementation of the method. You can either declare your method as abstract
, which means that the derived classes have to provide their own implementation:
public abstract void Sms();
or you can keep the method virtual and provide a default implementation in the base class:
public virtual void Sms()
{
// Default or no implementation goes here.
}
In the following code you're trying to cast IInterface
to MyClass
, which is probably not what you want.
public MyClass Xyz
{
get { return _myinterface; }
set { _myinterface = value; }
}
you're probably looking to return IInterface
instead:
public IInterface Xyz
{
get { return _myinterface; }
set { _myinterface = value; }
}
Upvotes: 0
Reputation: 2760
Change this
public abstract class Message
{
public virtual void Sms();
}
to this
public abstract class Message
{
public abstract void Sms();
}
You either give the virtual method a body, like so
public virtual void Sms() { }
or you mark it as abstract
public abstract void Sms();
EDIT:
Forgot about the second error. Change this
public MyClass Xyz
{
get { return _myinterface; }
set { _myinterface = value; }
}
to this
public IInterface Xyz
{
get { return _myinterface; }
set { _myinterface = value; }
}
Upvotes: 0