Reputation: 1293
I am trying to write some equivalent C# code to the following Java one:
public class XLexer extends antlr.CharScanner implements TokenStream {
protected int stringCtorState = 0;
public String mString() { return ""; }
public Token nextToken() {
resetText(); // exists in CharScanner class
return null; // will return something
}
public TokenStream plumb() {
return new TokenStream() {
public Token nextToken() {
resetText(); // exists in CharScanner class
if (stringCtorState >= 0) { String x = mString(); }
return null; // will return something
}
};
}
}
Can anyone give me an hint how to do it in C# because I am getting errors when defining the method nextToken inside the return statement.
thanks!
Upvotes: 0
Views: 247
Reputation: 8394
There are no anonymous classes in C# (in the sense you need). If you want to return an instance of a custom implementation of TokenStream
, you need to define it and give it a name.
Eg.:
public MyTokenStream {
public Token nextToken() {
// ...
}
}
public TokenStream plumb() {
return new MyTokenStream();
}
See:
http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html
http://www.25hoursaday.com/CsharpVsJava.html (anonymous inner classes are listed in the "Wish You Were Here" section; "this section describes language features and concepts that exist in Java and have no C# counterpart").
for reference.
As kan remarked, in C# (and Java 8, too) you would typically use a delegate or a lambda instead. If all that TokenStream does is returning a nextToken, it could be implemented like so:
public class TokenStream
{
}
public class SomeClass
{
public Func<TokenStream> Plumb()
{
// I'm returning a function that returns a new TokenStream for whoever calls it
return () => new TokenStream();
}
}
static void Main(string[] args)
{
var someClass = new SomeClass();
TokenStream stream = someClass.Plumb()(); // note double brackets
}
Think first-class functions in JavaScript, if it helps to grok it.
New Java brings functional interfaces, which is similar: http://java.dzone.com/articles/introduction-functional-1
Upvotes: 4
Reputation: 2406
Not sure if this is your desired result.
but the way I see it is you just want to return a TokenStream
object which has the method of nextToken
which returns an object Token
public class TokenStream
{
public Token nextToken()
{
return new Token();
}
}
that would be your TokenStream
class and then you could have a method/function else where which does the following
public TokenStream plumb()
{
return new TokenStream();
}
the usage of which would be
TokenStream ts = plumb();
Token t = ts.nextToken();
Upvotes: 1
Reputation: 28981
Use delegates instead. An example here: http://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx
Upvotes: 1