C # equivalent to creating an anonymous class that implements an interface

I recently started using C # and I wanted to find an equivalent method. I don’t know what it's called, so I’ll just show you the code.

With Java, I was able to create an interface like this:

public interface Event { public void execute(); } 

And pass this interface in the method parameter, for example:

 public class TestEvent { ArrayList<Event> eventList = new ArrayList<Event>(); public void addEvent(Event event){ eventList.add(event); } public void simulateEvent(){ addEvent(new Event() { public void execute(){ //functionality } } ); } public void processEvents(){ for(Event event : eventList) eventList.execute(); } } 

EDIT . My question is related to the simulatEvent method from the TestEvent class, and if such an action is possible with C #.

I wanted to know if there is a way to do something like this with C # (instantiating an interface in the simulateEvent method) and what it is actually called. Thanks!

+3
java c # interface anonymous-class
source share
2 answers

Woof ... ok, let me generalize a bit:

So, in Java, you need a way to skip functions. Java does not inherently support functions as first-class citizens, and this was one of the reasons for introducing anonymous classes - packaged groups of functions that can be declared inline and passed (as interfaces) to methods / other classes that will then call these functions.

In C #, functions are first-class citizens and can be declared as Delegates , Func<>s or Action<>s . Try comparison (grades):

Some kind of Java-y construct (my Java is pretty old, so bear with me):

 public interface IDoSomething { public int Return42(); public bool AmIPrettyOrNot(string name); public void Foo(); } public void Main(String[] args) { DoStuff(new IDoSomething() { public int Return42() { return 42; } public bool AmIPrettyOrNot(string name) { return name == "jerkimball"; } public bool Foo(int x) { ... } }); } public void DoStuff(IDoSomething something) { ... } 

The (very crude) equivalent of this in C # would be:

 public void Main(string[] args) { Func<int> returns42 = () => 42; Func<string,bool> amIPretty = name => name == "jerkimball"; Action<int> foo = x => {}; } 

Now, as others have noted, you usually see this pattern on the Java side when dealing with events - also on the C # side:

  public class Foo { // define the shape of our event handler public delegate void HandlerForBarEvent(object sender, EventArgs args); // declare our event public event HandlerForBarEvent BarEvent; public void CallBar() { // omitted: check for null or set a default handler BarEvent(this, new EventArgs()); } } public void Main(string[] args) { var foo = new Foo(); // declare the handler inline using lambda syntax foo.BarEvent += (sender, args) => { // do something with sender/args } foo.CallBar(); } 

Please note that we can also give him something with the same "form":

  public void MyHandler(object sender, EventArgs args) { // do stuff } public void Main(string[] args) { var foo = new Foo(); // that method above is the same "shape" as HandlerForBarEvent foo.BarEvent += MyHandler; foo.CallBar(); } 

But it is also used in Java to determine what threads do if memory serves (i.e. Runnable ) - and we can also do this in C #:

 var thread = new Thread((Action)(() => { // I'm the threads "run" method! }); thread.Start(); 

Now, the other things are listing:

 public void processEvents(){ for(Event event : eventList) eventList.execute(); } 

C # has the same idea, which is simply called otherwise:

 public void processEvents() { // edit: derp, 'event' is a keyword, so I'm // renaming this, since I won't get into why // you could also use @event... foreach(var evt in eventList) { evt.Execute(); } } 
+4
source share

EDIT: It seems your question is about anonymous implementations of an interface instead of events. You can use the built-in delegate type Action instead of your Event interface.

You can use Action instances using lambda expressions. Your code will look like this:

 public class TestEvent { List<Action> eventList = new List<Action>(); public void addEvent(Action event){ eventList.add(event); } public void simulateEvent(){ addEvent(() => { }); } public void processEvents(){ for(Action event : eventList) event(); } } 

The delegate syntax can be used instead of using () => { .. .} Ie delegate() { ... } in simulateEvent .

C # does not support anonymous interface implementations, so if your interface has several methods, you will need to define a specific class somewhere. Depending on the use, you can simply include this class in the properties of the delegate, which you can provide at creation, for example.

 public class Delegates { public Action Event { get; set; } public Func<string> GetValue { get; set; } } 

Then you can create it like this:

 var anon = new Delegates { Event = () => { ... }, GetValue = () => "Value" } 
+2
source share

All Articles