views:

134

answers:

4

Below is a quick example of what I am doing. Basically, I have multiple interfaces that can be implemented by 1 class or by separate classes, so I store each one in the application. My only question is about the variables myInterface, yourInterface, and ourInterface. Do they reference the same object or are there 3 different objects?

interface IMyInterface
{
    void MyFunction();
}

interface IYourInterface()
{
    void YourFunction();
}

interface IOurInterface()
{
    void OurFunction();
}

public class MainImplementation : IMyInterface, IYourInterface, IOurInterface
{
    public void MyFunction() { }
    public void YourFunction() { }
    public void OurFunction() { }
}

private IMyInterface myInterface;
private IYourInterface yourInterface;
private IOurInterface ourInterface;

static void Main(string[] args)
{
    myInterface = new MainImplementation() as IMyInterface;
    yourInterface = myInterface as IYourInterface;
    ourInterface = myInterface as IOurInterface;
}

Bonus: Is there a better way to do this?

+3  A: 

They reference the same instance. There is only one instance.

John Saunders
+5  A: 

They all reference the same object. So changes to them in the form of:

 ourInterface.X = ...

Will be reflected in 'all views'.

Effectively what you are doing with your casting (and I presume you meant your last one to be 'as IOurInterface') is giving a different 'view' of the data. In this case, each interface opens up one function each.

Noon Silk
Thanks. I had a feeling that was the case but I just needed verification.
daub815
+2  A: 

1 new = 1 object. They all reference the same instance.

JohnFx
A: 

They reference the same object. Casting an object to a different just tells the compiler that when a method is called on this object, use the method defined in this class as opposed to a different one.

CrazyJugglerDrummer