Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Interfaces vs. Func or Action [closed]

Tags:

c#

.net

I have been writing C# code for 10 years, but I am woefully weak on knowing exactly when to use an interface vs. using a Func or Action. It seems to me that in many places where a method on an interface is called, a Func or Action would work just as well. So, I guess my question is this. If I have an interface with just a single method, or perhaps a couple methods, is there any disadvantage to using a Func or Action instead? Using a Func or Action seems cleaner to me.

Thanks very much.

like image 480
Randy Minder Avatar asked Oct 31 '12 14:10

Randy Minder


People also ask

Is it necessary to implement all methods of interface Golang?

Implementing an interface in Go To implement an interface, you just need to implement all the methods declared in the interface. Unlike other languages like Java, you don't need to explicitly specify that a type implements an interface using something like an implements keyword.

What is the point of interfaces in Go?

Interfaces in GO Interface are the custom type that is used to specify a set of one or more method signatures which are allowed to create a variable of an interface type and this variable can be assigned with a concrete type value that has the methods the interface requires.

What is the equivalent of functions in Java?

In Java 8, the equivalents are the java. util. function. Function<T, R> and java.


2 Answers

I guess you can compare an Action or Func with an interface containing one method, with the difference that you can supply any Action or Func that meets the parameter / return value requirements, where when using interfaces, the supplied object must implement that interface.

Perhaps you could call Action and Func "anonymous single method interfaces".

If you look at the design perspective though, your class model would be a drawing of blocks without any lines between them.

like image 69
C.Evenhuis Avatar answered Sep 19 '22 19:09

C.Evenhuis


You should use delegates and lambda expressions if the implementations are expected to be very short (one or two lines), and especially if the implementations are expected to need local variables (closures).

like image 24
SLaks Avatar answered Sep 19 '22 19:09

SLaks