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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With