Cannot understand the behaviour of dotnet compiler while instantiating a class thru interface(C#)
- by Newbie
I have a class that impelemnts an interface. The interface is
public interface IRiskFactory
{
void StartService();
void StopService();
}
The class that implements the interface is
public class RiskFactoryService : IRiskFactory
{
}
Now I have a console application and one window service.
From the console application if I write the following code
static void Main(string[] args)
{
IRiskFactory objIRiskFactory = new RiskFactoryService();
objIRiskFactory.StartService();
Console.ReadLine();
objIRiskFactory.StopService();
}
It is working fine. However, when I mwrite the same piece of code in Window service
public partial class RiskFactoryService : ServiceBase
{
IRiskFactory objIRiskFactory = null;
public RiskFactoryService()
{
InitializeComponent();
objIRiskFactory = new RiskFactoryService(); <- ERROR
}
/// <summary>
/// Starts the service
/// </summary>
/// <param name="args"></param>
protected override void OnStart(string[] args)
{
objIRiskFactory.StartService();
}
/// <summary>
/// Stops the service
/// </summary>
protected override void OnStop()
{
objIRiskFactory.StopService();
}
}
It throws error: Cannot implicitly convert type 'RiskFactoryService' to 'IRiskFactory'. An explicit conversion exists (are you missing a cast?)
When I type casted to the interface type, it started working
objIRiskFactory = (IRiskFactory)new RiskFactoryService();
My question is why so?
Thanks.(C#)