Cannot understand the behaviour of C# compiler while instantiating a class thru interface

Posted by Newbie on Stack Overflow See other posts from Stack Overflow or by Newbie
Published on 2010-05-05T04:54:58Z Indexed on 2010/05/05 5:08 UTC
Read the original article Hit count: 114

Filed under:

I have a class that implements 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 cast to the interface type, it started working

objIRiskFactory = (IRiskFactory)new RiskFactoryService();

My question is why so?

© Stack Overflow or respective owner

Related posts about c#