Derek
Derek

Reputation: 11915

C# delegate to Java conversion

I am in the process of converting some code from C# to Java. I have never used C# before, but it has been pretty easy up to this point.

I have a line that looks like this in the C# file:

 coverage.createMethod = delegate (Gridpoint gp){
 //Some method stuff in here, with a return objecct
 }

What exactly is this trying to do? It seems a little bit like an inline class but I am not sure how to go about converting htis to java

Edit: more on the specific problem

In a file called STKDriver.java i have the following

 CoverageDefinitionOnCentralBody coverage = new CoverageDefinitionOnCentralBody(...);
 .
 .
 .
 DClass value = new DClass(STKDriver.class, "invoke", CoverageGrid.class);
 coverage.setGridPointCreationMethod(value);

In the fill DClass.java, which extends CreateCoverageGridPointForAccess I have the following:

 public DClass(Class class1, String string, Class<CoverageGridPoint> class2{}
 .
 .
 .
 public IServiceProvider invoke(CoverageGridPoint gridPoint){
    return something; //of the classtype Platform
 }

Is this done correctly? The class definitions are linked here:

http://www.agi.com/resources/help/online/AGIComponentsJava/index.html?page=source%2FWhatsNewJava.html

Notice that the class CreateCoverageGridPointForAccess is abstract and extends that Delegate class.

Does this implementation I have created look correct? I Can write in more code if necessary

Upvotes: 0

Views: 470

Answers (3)

Julien Lebosquain
Julien Lebosquain

Reputation: 41243

Tejs' answer is correct. However be careful because anonymous functions can use closures which means using an existing local variable declared in the outer function, from the anonymous delegate. I'm no Java programmer so I don't know if Java supports this.

Upvotes: 3

Justin Niessner
Justin Niessner

Reputation: 245449

coverage.createMethod is a Delegate.

The following code creates an anonymous method and assigns it to the delegate:

coverage.createMethod = delegate (Gridpoint gb) {
}

so that when somebody calls coverage.createMethod, your anonymous method gets executed.

Upvotes: 0

Tejs
Tejs

Reputation: 41256

This is an anonymous method in C#. It's technically the same thing as:

coverage.createMethod = new Func<Gridpoint, object>(SampleMethod);

public object SampleMethod(Gridpoint gp)
{
    return thingy; // Pseudo for return value
}

It's just a shortcut you can use to code less.

Upvotes: 3

Related Questions