What are interfaces and delegates in C #?

Since I am new to C #, I would like to learn about the interfaces and delegates in C #, the differences between them and the scripts that they should use. Please do not include any references, I would like the explanation to be in simple words.

+7
c #
source share
5 answers

Quote from C # in a nutshell.

A problem that can be solved with the help of a delegate can also be solved with the help of an interface. For example, the following explains how to solve a filter problem using the ITransformer interface:

 public interface ITransformer { int Transform (int x); } public class Util { public static void TransformAll (int[] values, ITransformer t) { for (int i = 0; i < values.Length; i++) values[i] = t.Transform (values[i]); } } class Squarer : ITransformer { public int Transform (int x) { return x * x; } } ... static void Main() { int[] values = { 1, 2, 3 }; Util.TransformAll (values, new Squarer()); foreach (int i in values) Console.WriteLine (i); } 

Delegate design may be a better choice than interface design if one or more of these conditions are true:

  • An interface defines only one Method.
  • Multicast required.
  • The subscriber needs to implement the interface several times.

In the ITransformer example, we do not need multicast. However, the interface defines only one method. In addition, our subscriber may need to implement ITransformer several times to support various transformations, such as square or cube. With interfaces, they were forced to write a separate type for each transformation, because Test can implement ITransformer only once. This is rather cumbersome:

 class Squarer : ITransformer { public int Transform (int x) { return x * x; } } class Cuber : ITransformer { public int Transform (int x) {return x * x * x; } } ... static void Main() { int[] values = { 1, 2, 3 }; Util.TransformAll (values, new Cuber()); foreach (int i in values) Console.WriteLine (i); } 

And here is the code with the delegate

 public delegate int Transformer (int x); class Util { public static void Transform (int[] values, Transformer t) { for (int i = 0; i < values.Length; i++) values[i] = t (values[i]); } } class Test { static void Main() { int[] values = { 1, 2, 3 }; Util.Transform (values, Square); // Dynamically hook in Square foreach (int i in values) Console.Write (i + " "); // 1 4 9 } static int Square (int x) { return x * x; } } 
+8
source share

An interface is a contract - it defines the methods and properties that any implementation class must have, and thus, any user of the interface will know that they exist and can use them.

A delegate is a callback site — it defines a method signature that can call any method that has the same signature.

See delegates and interfaces in the C # programming guide.

An example interface is an IEnumerable interface. It contains only one element - GetEnumerator . Any object that implements this interface will have this method, and any code using such an object can call this method.

An example of a delegate is the delegate Predicate<T> . This is a generic delegate, defined as follows:

 public delegate bool Predicate<in T>(T obj); 

This means that it takes any type T and returns a bool . Any method that takes one type parameter and returns bool is a match for this delegate and can be used with it.

Since delegates are also objects, they can be passed to functions. Thus, any function that has a Predicate<T> delegate can pass in any mathod that matches it. Many of the Linq statements have delegates as parameters. Examples are here .

+11
source share

An interface can be considered as a functional definition (or contract). In the real world, many objects have well-known interfaces that make them largely (but not completely) interchangeable.

For example, take a car. Once you learn how to drive a car, you will learn the “Car Driving Interface”. You know that there will be an Accelerate () function and a Stop () function and, as a rule, the ShiftGears () function (even if it just takes it out of the park and sends it to disk). There is also a Steer () function and a SignalTurn () function.

There is no guarantee that any given implementation will do the same. For example, Toyota may have a Stop () method in the CarDriving interface, which actually calls Accelerate ().

The car can support additional locks, such as the SeatBelt interface or the radio interface. Although each implementation of these objects may differ, there is always a basic set of functions that is common to all types of these objects. This allows them to be used interchangeably to a large extent without having to relearn another interface.

Interfaces in C # are similar. Different implementations of objects may contain the same implementation of an interface, and what they do may be different, but you can consider one object that implements a particular interface in the same way you handle another object that implements the same interface.

If you understand what inheritance is, then another way to think about interfaces is that they are the same as the class, but they have no implementation. Therefore, when a class inherits from another class, it inherits both the inteface and implementation classes. If a class inherits only an interface, then it lacks an implementation, and the new class itself must create this implementation.

The delegate is completely different. A delegate is, among other things, a pointer to a function that is an object. A function pointer is a variable similar to other variables, but it is “delegate” and not “int” or “string”. And instead of storing data, it contains a pointer to a method (along with some status information) so that you can dynamically call different functions at run time.

In the following code, the call to "foo" is fixed. At runtime, you cannot decide whether you want to call the "bar":

 DoSometing() { foo(); } 

If instead you did something like the following, you can pass different methods as arguments to your method and call them dynamically:

 DoSomething(MyFunction func) { MyFunction myfunc = func; myfunc(); } 

Delegates can do more than that, but this is the main way to think about them.

+5
source share

Well, I can speak English with you. You are a man. I can speak with any person in English; I do not need to know all the people on earth to speak English with them; all i care about is that they speak english.

OK, so a person is an object. English interface.

Many people implement the IEnglish interface!

Now apply this in the classic engineering sense. I have a car and a car battery. The car does not care about what type of battery, where it was made, or in what form. The battery does not care about the car. They are functionally abstract from each other.

The battery provides power and implements the IBattery interface. The car will ONLY accept objects that implement IBattery (i.e. Physical objects that are car batteries !!)

Semantically, interfaces and delegates are pretty much equivalent. The interface defines what the object does (methods and properties) ... and the delegate determines what the particular method does. Delegates describe the parameters of a function or method .... they are pointers to a function of a safe type. I will need to think more to come up with a real life example for this.

+3
source share

An interface is a collection of methods associated with a single object. (Side note: objects can expose several interfaces, which allows them to demonstrate several "personalities").

A delegate is an abstraction of a single method call. A delegate call has the effect of calling another piece of code that the caller knows nothing about.

A somewhat simplified view of things that nevertheless add flavor is to consider a delegate as a special case of an interface using a single method.

+2
source share

All Articles