Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OOPS Concepts: What is the difference in passing object reference to interface and creating class object in C#?

I have a class, CustomerNew, and an interface, ICustomer:

public class CustomerNew : ICustomer
{
    public void A()
    {
        MessageBox.Show("Class method");
    }

    void ICustomer.A()
    {
        MessageBox.Show("Interface method");
    }


    public void B()
    {
        MessageBox.Show("Class Method");
    }
}

public interface ICustomer
{
    void A();
}

I am very confused between these two code of lines.

ICustomer objnew = new CustomerNew();
CustomerNew objCustomerNew = new CustomerNew();
objnew.B(); // Why this is wrong?
objCustomerNew.B(); // This is correct because we are using object of class

The first line of code means we are passing object reference of CustomerNew class in objnew, am I correct? If yes, then why can I not access method B() of the class with interface objnew?

Can someone explain about these two in detail.

like image 705
Gaurav123 Avatar asked Jun 01 '15 09:06

Gaurav123


1 Answers

Interfaces have many features and usages but one central thing is the ability to present functionality to the outside world in an agreed upon contract.

Let me give you an example. Consider a soda vending machine. It has a slot or two for you to input coins, a few buttons for you to choose the right type of soda and a button to dispense the soda (unless the choice button also does that).

Now, this is an interface. This hides the complexity of the machine behind the interface and presents a few choices to you.

But, and here is the important part, internally the machine has a lot of functionality and it may even have other buttons and knobs, typically there for the maintenance people to test or operate the machine when there is something wrong, or when they have to empty it for money or fill it with soda.

This part of the machine is hidden from you, you only get access to whatever the creators of the external interface added to that interface.

You don't even know how the machine actually operates behind the scenes. I could create a new vending machine that teleports sodas in from a nearby factory and teleports the coins you added directly to the bank and you would be none the wiser. Not to mention that I would be rich, but that's another story.

So, back to your code.

You explicitly declared objnew as ICustomer. Whatever you put behind this interface is hidden. You only get access to whatever it is that is declared as part of that interface.

The other variable was declared as having the type of the underlying object, as such you have full access to all of its public functionality. Think of it like unlocking the vending machine and using it with the front open.

like image 58
Lasse V. Karlsen Avatar answered Oct 22 '22 12:10

Lasse V. Karlsen