Why should I use Interfaces in C # when I can implement methods directly

I know this is a very simple question, but the interviewer asked me a very trick, and I was helpless :(

I only know the material or theoretical definition of an interface, and also implemented it in many projects that I worked on. But I really don’t understand why and how it is useful.

I also do not understand one thing about the interface. for example we use

conn.Dispose(); in the finally block. But I don’t see that the class implements or inherits the IDisposable interface ( SqlConnection ) of class I. I am wondering how I can simply name the method name. Also in the same, I do not understand how the Dispose method works, because we need to implement the function body with our own implementation for all interface methods. So how are interfaces accepted or called contracts? These questions have continued to this day, and frankly, I have never seen a single good thread that could explain my questions in a way that I could understand.

MSDN as usual looks very scary, and there is no single line (people, kindly excuse me, who is at a high level of development, I firmly feel that any code or article should reach the mind of anyone who sees it, therefore, like many others let's say MSDN is not used).

The interviewer said:

He has 5 methods, and he is happy to implement it directly in the class, but if you need to switch to an abstract class or interface, which one to choose and why? I answered him all the materials that I read on different blogs, talking about the advantages and disadvantages of both the abstract class and the interface, but he is not convinced, he is trying to understand "Why the interface" in general. "Why an abstract class" in general, even if I can implement the same methods only once, and not change it.

I do not see a place on the network, I could get an article that would clearly explain to me about the interfaces and its functioning. I am one of those many programmers who still do not know about interfaces (I know the theoretical and methods that I used), but are not satisfied that I clearly understood this.

+106
c # oop class interface abstraction
Jun 06 '12 at 13:05
source share
15 answers

Interfaces are excellent when you want to create something like this:

 using System; namespace MyInterfaceExample { public interface IMyLogInterface { //I want to have a specific method that I'll use in MyLogClass void WriteLog(); } public class MyClass : IMyLogInterface { public void WriteLog() { Console.Write("MyClass was Logged"); } } public class MyOtherClass : IMyLogInterface { public void WriteLog() { Console.Write("MyOtherClass was Logged"); Console.Write("And I Logged it different, than MyClass"); } } public class MyLogClass { //I created a WriteLog method where I can pass as a parameter any object that implements IMyLogInterface. public static void WriteLog(IMyLogInterface myLogObject) { myLogObject.WriteLog(); //So I can use WriteLog here. } } public class MyMainClass { public void DoSomething() { MyClass aClass = new MyClass(); MyOtherClass otherClass = new MyOtherClass(); MyLogClass.WriteLog(aClass);//MyClass can log, and have his own implementation MyLogClass.WriteLog(otherClass); //As MyOtherClass also have his own implementation on how to log. } } } 

In my example, I could be a developer who writes MyLogClass , and other developers could create their own classes, and when they wanted to enter, they implemented the IMyLogInterface interface. This is how they asked me what they need to implement in order to use the WriteLog() method in MyLogClass . They will find the answer in the interface.

+89
Jun 06 '12 at 13:30
source share

One of the reasons I use interfaces is because it increases the flexibility of the code. Suppose we have a method that takes an object of a class of type Account as a parameter, for example:

 public void DoSomething(Account account) { // Do awesome stuff here. } 

The problem with this is that the method parameter is fixed to implement the account. It’s good if you never need another type of account. Take this example, which instead uses the account interface as a parameter.

 public void DoSomething(IAccount account) { // Do awesome stuff here. } 

This solution is not implementation-specific, which means that I can pass it SuperSavingsAccount or ExclusiveAccount (both implement the IAccount interface) and get different behavior for each implemented account.

+49
Mar 08 '16 at 12:45
source share

Interfaces are contracts that performers must follow. Abstract classes allow you to conclude contracts plus common implementations - something that interfaces cannot have. Classes can implement and inherit multiple interfaces. Classes can extend only one abstract class.

Why interface

  • You have no default implementation or common code
  • You want to share contracts with data (web services, SOA).
  • You have different implementations for each interface developer ( IDbCommand has SqlCommand and OracleCommand , which implement the interface in different ways)
  • You want to support multiple inheritance .

Why Abstract

+41
Jun 06 2018-12-06T0014
source share

enter image description here

So in this example, PowerSocket knows nothing more about other objects. All objects depend on the power provided by PowerSocket, therefore they implement IPowerPlug and at the same time can connect to it.

Interfaces are useful because they provide contracts that objects can use to work together without the need to know anything else about each other.

+24
Aug 25 '17 at 12:18
source share

In one word - because of Polymorphism !

If you are "Programming an interface, not an implementation", you can enter different objects that use the same interface (type) as an argument. Thus, your method code is not associated with any implementation of another class, which means that it is always open for working with newly created objects of the same interface. (Principle of opening / closing)

  • Take a look at Injection Dependency and definitely read Design Patterns - Elements of reusable object-oriented GOF software.
+20
Nov 27 '13 at 23:09
source share

C # does not have duck printing - just because you know that a particular method is implemented through a set of specific classes does not mean that you can treat them anyway with respect to calling this method. Implementing an interface allows you to consider all classes that implement it as things of the same type with respect to what defines this interface.

+4
Jun 06 '12 at 13:12
source share

Using the interface, you can do the following:

1) Create segregated interfaces that offer various abbreviations for your implementation, allowing you to use a more cohesive interface.

2) Allow the use of several methods with the same name between the interfaces, because, you do not have an inconsistent implementation, just a signature.

3) You can execute the version and remove your interface regardless of your implementation, ensuring that the contract is completed.

four). Your code can rely on abstraction rather than nodule, which allows intelligent injection, including injection test mocks, etc.

There are many more reasons, I'm sure these are just a few.

An abstract class allows you to have a partially concrete basis for work, this is not the same as an interface, but has its own qualities, such as the ability to create a partial implementation using the template method template.

+2
Jun 06 2018-12-06T00:
source share

I believe that a lot of blood has already been shed by asking these questions, and many are trying to solve these problems by explaining robot-like terms that no normal person can understand.

So first. find out why the interface and why abstraction you need to find out why they are needed. I personally found out about this when applying the Factory class. You will find a good tuturial at this link

Now give the link to the link to the link that I have already given.

You have a class Car , which can change at the request of the user (for example, add Truck, Tank, Airplane, etc. And if we have

 public class clsBike:IChoice { #region IChoice Members public string Buy() { return ("You choose Bike"); } #endregion } 

and

 public class clsCar:IChoice { #region IChoice Members public string Buy() { return ("You choose Car"); } #endregion } 

and both have an ihoice contract that just says my class should have a Buy method

 public interface IChoice { string Buy(); } 

Now you see that this interface only applies the Buy() method, but allows the inherited class to decide what to do when they implement it. This is a limitation of the interface, using a pure interface, you can end up repeating some task that we can implement automatically using abstact. In our example, let's say that every car has a discount.

 public abstract class Choice { public abstract string Discount { get; } public abstract string Type { get; } public string Buy() { return "You buy" + Type + " with " + Discount; } public class clsBike: Choice { public abstract string Discount { get { return "10% Discount Off"; } } public abstract string Type { get { return "Bike"; } } } public class clsCar:Choice { public abstract string Discount { get { return " $15K Less"; } } public abstract string Type { get { return "Car"; } } } 

Now, using the Factory class, you can achieve the same, but using the abstract, you allow the base class to execute the Buy() method.

Summary: contracts The interface allows the inherit class to execute the implementation while the Abstract class Contracts can initialize the implementation (which can be overridden by the Inherit class)

+2
Nov 11 '15 at 12:51 on
source share

As a real example of @ user2211290 answer:

Both of Array and List have an IList interface. Below we have string[] and List<string> as well as some common tests using IList :

 string[] col1 = { "zero", "one", "two", "three", "four"}; List<string> col2 = new List<string>{ "zero", "one", "two", "three"}; static void CheckForDigit(IList collection, string digit) { Console.Write(collection.Contains(digit)); Console.Write("----"); Console.WriteLine(collection.ToString()); } static void Main() { CheckForDigit(col1, "one"); //True----System.String[] CheckForDigit(col2, "one"); //True----System.Collections.Generic.List'1[System.String] //Another test: CheckForDigit(col1, "four"); //True----System.String[] CheckForDigit(col2, "four"); //false----System.Collections.Generic.List'1[System.String] } 
+2
Jan 17 '19 at 13:34
source share

You can inherit only one abstract class. You can inherit from multiple interfaces. This determines what I use for most cases.

The advantage of an abstract class is that you can have a basic implementation. However, in the case of IDisposable, the default implementation is useless, since the base class does not know how to clean things up properly. Thus, the interface will be more appropriate.

+1
Jun 06 2018-12-06T0014
source share

Both abstract classes and interfaces are contracts.

The idea of ​​the contract is that you indicate some kind of behavior. If you say that you have completed, you have agreed to a contract.

Choice of abstract over interface.

Any abstract object of an abstract class implements a contract.

against

Any class that implements the interface will execute the contract.

So, you use abstract when you want to indicate some kind of behavior, all descendants must implement and preserve themselves by defining a separate interface, but now everything that corresponds to this effectively aggregated contract should be a descendant.

+1
Jun 06 2018-12-06T00:
source share

Interfaces are designed to create an abstraction (archetype) of abstraction (classes) of reality (objects).

Interfaces must specify the terms of the contract without providing the implementation provided by the classes.

Interfaces are specifications, as well as a human-readable shell for virtual tables.

  • Interfaces are development-time artifacts that define the stationary behavior of a concept, because it is one and static.

  • Classes are implementation-time artifacts that define the mobile structure of reality when it interacts and moves.

What is an interface?

When you watch a cat, you can say that it is an animal with four legs, a head, a body, a tail and hair. You can see that he can walk, run, eat and meow. And so on.

You have just defined an interface with its properties and operations. Thus, you did not determine any mode of action, but only functions and capabilities, not knowing how everything works: you determined abilities and differences.

As such, it is not really a class yet, although in UML we call it a class in a class diagram. Don’t be embarrassed here, because in UML the interface is slightly different from the interface in C #: it looks like a partial access point to an abstraction atom. Thus, we said that a class can implement several interfaces. As such, this is one and the same thing, but not because the interfaces in C # are used both for abstraction and for limiting this abstraction as an access point. These are two different uses. Thus, a class in UML represents an interface that is fully connected to a programming class, while a UML interface represents a section decoupling interface for a programming class. Indeed, the class diagram in UML does not care about the implementation, and all of its artifacts are at the programming interface level. Although we map UML classes to programming classes, this is a transfer of an abstract abstraction to a concrete abstraction. There is a subtlety that explains the dichotomy between the design domain and the programming domain.

Interfaces also allow you to simulate multiple inheritance when it is not accessible in an inconvenient way. For example, the cat class will implement the cat interface, which inherits from the animal interface. This cat class will also implement these interfaces: walk, run, eat and make sound. This compensates for the lack of multiple inheritance at the class level, but each time you need to redefine everything, and you cannot, at best, consider reality, as reality itself does.

Also in C #, for example, interfaces can compensate for the lack of true universal polymorphism on open types without actually achieving the goal, because you have lost strong typing.

In addition, interfaces are the human representation of virtual tables created by the compiler on the classes you create.

In the end, interfaces are necessary so that incompatible systems can exchange data without worrying about the implementation and management of objects in memory, as was presented in the (distributed) general object model.

What is a class?

Having defined the contraction of reality from an external point of view, you can describe it from an internal point of view: this is a class in which you define data processing and message management to allow your embodied reality to come to life and interact thanks to objects using instances.

Thus, in UML, you implement a fractal immersion in the wheels of a machine and describe states, interactions, etc., in order to be able to implement an abstraction of a fragment of reality that you want to work with.

Thus, the abstract class is somehow equivalent to the interface from the point of view of the compiler.

Additional Information

Protocol (Object Oriented Programming)

C # - Interfaces

C # - Classes

Virtual method table

+1
Sep 30 '19 at 19:16
source share

Interfaces allow the class designer to make available methods very understandable to the end user. They are also an integral part of polymorphism.

0
Jun 06 2018-12-06T00:
source share

I will not publish the definition of an interface against an abstract class, because I think you know this theory well, and I assume that you know the principles of SOLID, so let's get started.

As you know, interfaces cannot have any code, so dis-vantage is pretty easy to understand.

if you need to initialize the property of your class that provides the constructor, or if you want to provide part of the implementation, the abstract class will fit in well with the interface, which will prevent you from doing this.

So, in general, you should prefer an abstract class for interfaces when you need to provide a constructor or any code with a client that inherits / extends your class

0
Jun 06 2018-12-06T0014
source share

An abstract class is divided into categories for related objects, where unrelated objects can be used as interfaces.

For example, if I have two entities, say, Animal and Human, then I’ll go for an interface where, as if I have to elaborate on Tiger, lion and want to associate with Animal, then we will select Animal Abstract class ..

will look below

  Interface ____|____ | | Animal Human Animal (Abstract class) __|___ | | Tiger Lion 
-2
Nov 27 '13 at 14:06
source share



All Articles