What is the difference between instantiating using an interface and a derived class in .net, can anyone tell me briefly?

interface Icustomer
{
    void sample();
}

public  class customer : Icustomer
{
   public void sample()
    {
        Console.WriteLine("This is sample Method");
    }
}

class Program
{
    static void Main()
    {
       Icustomer ob1 = new customer();
        customer ob2 = new customer();
    }
+4
source share
3 answers

There is no difference for your specific example, but it is very useful to create an instance against the variable Interface, since it helps in writing specific code that is independent of the instance.

for instance

interface IPizza {    
    public String Bake();  }  

public class CountrySpecial: IPizza   {
     public String Bake() 
     {
      //add country special toppings 
     } }

public class FarmHouse: IPizza   {
     public String Bake()
     { 
     //add farm house special toppings 
     } }

public class Order   {
    public void PlaceOrder(IPizza pizza) 
    {
     pizza.Bake(); 
     //pack and ship 
    } }

Now you can do amazing things, regardless of the specific initialization, for example:

class Program
{
    static void Main()
    {
       Order ord = new Order(); 
       //customer ordered for country special
       ord.PlaceOrder(new CountrySpecial()); //this will call bake of CountrySpecial
       //maybe some other customer ordered for different pizza, and we can change at run-time(thanks to our design!)
       ord.PlaceOrder(new FarmHouse()); // this will call Bake of FarmHouse

    }
}

Using the above design, we can add as many types of pizza as we want, without even changing the code for ordering them!

In addition, although you asked in the context of .net, but this has nothing to do with the language, because it is a design issue;)

Hope this helps!

+4

. . - , . , , .

0

, Icustomer. , , .

, , .

, Icustomer

public class customerA : Icustomer
public class customerB : Icustomer

, ,

Icustomer c;
if (test)
    c = new customerA();
else
    c = new customerB();

c.sample();

0

Source: https://habr.com/ru/post/1545579/


All Articles