Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write c# implementation of abstract class inline?

I found a great example of code written in java for the use of a timer / timertask classes...

I am currently turning this into c# for a 'Mono for Android' implementation, but having trouble with converting the inline implementation of the abstract class TimerTask

// Here's the original java code

private void resetMapChangeTimer()    
{        
mChangeDelayTimer.schedule(
new TimerTask()        
    {            
      @Override            
      public void run()            
      {                
        // Some code to run           
      }        
    }, longTenSeconds);    
}

When I implement this in c#, I would like to create an inherited class from TimerTask (abstract class) and the run method etc in-line without having to create a seperate class (extending TimerTask) as the java code above does.

Can anyone advise me on the c# syntax to create this abstract class inline instead of creating a seperate class just to inherit and implement TimerTask?

like image 741
Bonshaw Avatar asked Jun 10 '12 15:06

Bonshaw


2 Answers

C# doesn't support inline classes as in Java. You could define anonymous methods but not entire classes. So you will have to define a separate class that implements the abstract class.

like image 191
Darin Dimitrov Avatar answered Nov 11 '22 23:11

Darin Dimitrov


As Darin says, an anonymous function is the way to go here. You're only trying to specify one bit of behaviour, so just make the method accept an Action and then the caller can use an anonymous function (either an anonymous method or a lambda expression). The calling code would look like this:

changeDelayTimer.Schedule(() => {
    // Code to run
}, TimeSpan.FromSeconds(10));

Or if you had a lot of code, you'd want to use a method, with a method group conversion:

changeDelayTimer.Schedule(MethodContainingCode, TimeSpan.FromSeconds(10));

In Java I rarely find I want to do more than override a single method within an anonymous inner class anyway - so anonymous functions in C# almost always work just as well here.

When porting code from Java to C#, it's important not to try to preserve Java idioms - preserve the same goals, but porting to a .NET idiom, which in this case is using a delegate to represent a single piece of behaviour in an abstract way.

like image 43
Jon Skeet Avatar answered Nov 11 '22 23:11

Jon Skeet