Java Equivalent code in C# - c#

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!

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

Use delegates instead. An example here: http://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx

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();

Related

Is it possible to infer this generic type, for type-safe callback?

Is there a way to get rid of the CS0411 error below, and not have to explicitly state the type?
Also do not want to have to use reflection.
var router = new ExampleRouter();
var controller = new ExampleWebController();
// compiles, but not elegant
router.MapPost<string>("/api/bar", controller.ProcessString);
// error CS0411: can't infer type
router.MapPost("/api/foo", controller.ProcessString);
class ExampleWebController {
public ExampleWebController() { }
public bool ProcessNumber(int v) { return true; }
public bool ProcessString(string v) { return true; }
}
class ExampleRouter {
public ExampleRouter() { }
public void MapPost<TBody>(string path, Func<TBody, bool> handler) {
// Save typeof(TBody), since TBody will actually be a class type we
// will construct for each callback
var body_type = typeof(TBody);
}
}
Yep, as someone's mentioned in comments one solution is to pass in the data as a parameter:
public void MapPost<TBody>(string path, Func<TBody, bool> handler, Tbody data) {
object dataType = data.GetType();
}
The reason your code is "inelegant" as you've said, is because the order of your generic arguments specifies an input type (TBody) and an output type (bool). However, in your calls to MapBody, you are only providing methods that return boolean results, so that the compiler doesn't know what to use for the value of TBody.
This is the origin of the CS0411 error you are receiving. The only way around it is to provide a generic type argument at the point of call.
This is why this code works, and should be what you use going forward:
var router = new ExampleRouter();
var controller = new ExampleWebController();
// compiles, but not elegant
router.MapPost<string>("/api/bar", controller.ProcessString);
A bit of a self answer here. If I change it to this, the MapPost() code looks elegant, which was my goal. HOWEVER, I have lost some compile time checking -- for example anything can be passed in as a "handler". I will post a new question on how I refine this.
var router = new ExampleRouter();
var controller = new ExampleWebController();
// We will have to do runtime validation that controller.ProcessString is a
// legal callback (which isn't ideal, but still fine).
// An improvement would be to add some kind of generic constraints?
router.MapPost("/api/foo", controller.ProcessString);
class ExampleWebController {
public ExampleWebController() { }
public bool ProcessNumber(int v) { return true; }
public bool ProcessString(string v) { return true; }
}
class ExampleRouter {
public ExampleRouter() { }
public void MapPost<TFunc>(string path, TFunc handler) {
var func_type = typeof(TFunc);
Console.WriteLine(func_type); // Prints "System.Func"
var args = func_type.GetGenericArguments();
foreach (var arg in args) {
// Prints "System.String", "System.Boolean"...awesome
Console.WriteLine(arg);
}
}
}

Is it possible to have method only accessible after certain conditions are met?

I'm trying to make a method, MethodA, only accessible when bool, executable, is true. Otherwise an other method, MethodB, is accessible. For example:
private bool executable = true;
public int MethodA(); <-- // Is accessible from outside of the class because executable is true
public string MethodB() <-- // Is not accessible because executable is true
The main reason I'm trying to do this is because the 2 methods return 2 different types. So my question is, is this even possible?
Option #1
You may be able to get what you want using Polymorphism and Generics. This would also allow you to add additional method strategies if needed.
public interface IMethodStrategy<out T>
{
T DoSomething();
}
public class MethodOneStrategy : IMethodStrategy<string>
{
public string DoSomething()
{
return "This strategy returns a string";
}
}
public class MethodTwoStrategy : IMethodStrategy<int>
{
public int DoSomething()
{
return 100; // this strategy returns an int
}
}
// And you would use it like so...
static void Main(string[] args)
{
bool executable = true;
object result = null;
if (executable)
{
MethodOneStrategy methodA = new MethodOneStrategy();
result = methodA.DoSomething();
}
else
{
MethodTwoStrategy methodB = new MethodTwoStrategy();
result = methodB.DoSomething();
}
}
Option #2
Another option could be a simple proxy method to wrap the worker methods.
// proxy class to wrap actual method call with proxy call
public class MethodProxy
{
public object DoMethodWork(bool executable)
{
if (executable)
{
return MethodA();
}
else
{
return MethodB();
}
}
private int MethodA()
{
return 100; // returns int type
}
private string MethodB()
{
return "this method returns a string";
}
}
// used like so
static void Main(string[] args)
{
var methodProxy = new MethodProxy();
object result = methodProxy.DoMethodWork(true);
}
Use conditional compilation for this.
#if RELEASE
public string MethodB() ...
#endif
Although I have my doubts about whether you need this or not. Your rationale doesn't make much sense.
You can use different Build Configurations to manage your conditional compile symbols.
if(executable)
MethodA();
else
MethodB();
OR
if(executable)
MethodA();
MethodB();
not entirely sure what you are trying to do but this could be one way, probably not the most efficient way but could work depending on what you are trying to do?
public int MethodA(executable)
{
if(executable = true)
{
//do stuff
}
else
{
return -1;
}
}
public String MethodB(executable)
{
if(executable = false)
{
//do stuff
}
else
{
String error = "MethodB cannot be used right now";
return error;
}
}

How do I refactor similar methods to eliminate duplicate setup and exception handling?

Context:
I consume a ERP WebService exposing N methods like:
FunctionNameResponse FunctionName(FunctionNameQuery query)
I made a functional wrapper in order to:
Get rid off wrapper object FunctionNameResponse and FunctionNameQuery, that every method has.
One instance of the WebService for all the program.
Investigate and log error in the wrapper.
Investigate Slow running and Soap envelope with IClientMessageInspector
Duplicated code:
For each of the methods of the WebService I end up with around thirty lines of code with only 3 distinct words. Type response, type query, method name.
public FooResponse Foo(FooQuery query)
{
// CheckWebServiceState();
FooResponse result = null;
try
{
result =
WSClient
.Foo(query)
.response;
}
catch (Exception e)
{
// SimpleTrace();
// SoapEnvelopeInterceptorTrace();
// TimeWatch_PerformanceIEndpointBehaviorTrace();
}
return result;
}
I would like to reduce those repetition. In order to :
Make it easier to add a Method;
Avoid copy pasting programming with no need to understand what you are doing.
Easier to add specific catch and new test without the need to copy past in every method.
The following code work and exist only in the imaginary realm. It's a not functional sketch of my solution using my limited understanding.
public class Demo
{
public enum WS_Method
{
Foo,Bar,FooBar
}
public class temp
{
public Type Query { get; set; }
public Type Response { get; set; }
public WS_Method MethodName { get; set; }
}
public static IEnumerable<temp> TestFunctions =>
new List<temp>
{
new temp{Query=typeof(FooQuery), Response=typeof(FooResponse), MethodName=WS_Method.Foo },
new temp{Query=typeof(BarQuery), Response=typeof(BarResponse), MethodName=WS_Method.Bar },
new temp{Query=typeof(FooBarQuery), Response=typeof(FooBarResponse), MethodName=WS_Method.FooBar },
};
public static void Run()
{ // Exemple of consuming the method
var input = new BarQuery { Bar_Label = "user input", Bar_Ig = 42 };
BarResponse result = Execute<BarQuery, BarResponse>(input);
}
public static T2 Execute<T1,T2>(T1 param) {
//Get temp line where Query type match Param Type.
var temp = TestFunctions.Single(x => x.Query == typeof(T1));
var method = typeof(DemoWrapper).GetMethod(temp.MethodName.ToString(), new Type[] { typeof(T1) });
var wsClient = new DemoWrapper();
T2 result = default(T2);
try
{
result =
method
.Invoke(wsClient, new object[] { param })
.response;
}
catch (Exception e)
{
// SimpleTrace();
// SoapEnvelopeInterceptorTrace();
// TimeWatch_PerformanceIEndpointBehaviorTrace();
}
return result;
}
}
I know the reflection is heavy and perhaps it's not the right way to achieve this refactoring. So the question is:
How do I refactor those function?
attachment : Live demo https://dotnetfiddle.net/aUfqNp.
In this scenario:
You have a larger block of code which is mostly repeated
The only difference is a smaller unit of code that's called inside the larger block
You can refactor this by passing the smaller unit of code as a Func or Action as a parameter to the larger function.
In that case your larger function looks like this:
public TResponse GetResponse<TResponse>(Func<TResponse> responseFunction)
{
var result = default(TResponse);
try
{
result = responseFunction();
}
catch (Exception e)
{
// SimpleTrace();
// SoapEnvelopeInterceptorTrace();
// TimeWatch_PerformanceIEndpointBehaviorTrace();
}
return result;
}
The individual functions which call it look like this, without all the repeated code:
public FooResponse Foo(FooQuery query)
{
return GetResponse(() => WSClient.Foo(query));
}
Here's another approach where you keep the methods but have them all call a method that handles the duplication.
public class Demo
{
private _wsClient = new DemoWrapper();
public static void Run()
{ // Exemple of consuming the method
var input = new BarQuery { Bar_Label = "user input", Bar_Ig = 42 };
BarResponse result = Bar(input);
}
public FooResponse Foo(FooQuery foo) =>
Execute(foo, query => _wsClient.Foo(query));
public BarResponse Bar(BarQuery bar) =>
Execute(bar, query => _wsClient.Bar(query));
public FooBarResponse FooBar(FooBarQuery fooBar) =>
Execute(fooBar, query => _wsClient.FooBar(query));
private static TResponse Execute<TQuery ,TResponse>(
TQuery param, Func<TQuery, TResponse> getResponse)
{
//Get temp line where Query type match Param Type.
var result = default(TResponse);
try
{
result = getResponse(query);
}
catch (Exception e)
{
// SimpleTrace();
// SoapEnvelopeInterceptorTrace();
// TimeWatch_PerformanceIEndpointBehaviorTrace();
}
return result;
}
}

How to implement code like SomeObject.SomeFunction().SomeOtherFunction();

Today, I searched a line of code which was written like:
SomeObject.SomeFunction().SomeOtherFunction();
I am unable to understand this. I tried to search it on Google about this but no luck.
Please help me to understand this.
SomeObject has a function called SomeFunction(). This function returns an object (of an unknown type for us, based on your example). This object has a function called SomeOtherFunction().
The question "how to implement" is a bit vague to answer, though.
Consider the following
public class FirstClass
{
public SecondClass SomeFunction()
{
return new SecondClass();
}
}
public class SecondClass
{
public void SomeOtherFunction()
{
}
}
So the following are equivalent.
FirstClass SomeObject = new FirstClass();
SomeObject.SomeFuntion().SomeOtherFunction();
OR
FirstClass SomeObject = new FirstClass();
SecondClass two = SomeObject.SomeFuntion();
two.SomeOtherFunction();
This is called Fluent coding or method chaining and is a method of programming that allows you to chain commands together. It is very common in LINQ where you might have something like this:
var result = myList.Where(x => x.ID > 5).GroupBy(x => x.Name).Sort().ToList();
This would give you all the records greater than 5, then grouped by name, sorted and returned as a list. The same code could be written in long hand like this:
var result = myList.Where(x => x.ID > 5);
result = result.GroupBy(x => x.Name);
result = result.Sort();
result = result.ToList();
But you can see this is much more long winded.
This style of programming called FluentInterface style.
Eg:
internal class FluentStyle
{
public FluentStyle ConnectToDb()
{
// some logic
return this;
}
public FluentStyle FetchData()
{
// some logic
return this;
}
public FluentStyle BindData()
{
// some logic
return this;
}
public FluentStyle RefreshData()
{
// some logic
return this;
}
}
And the object can be created and method can be consumed as below;
var fluentStyle = new FluentStyle();
fluentStyle.ConnectToDb().FetchData().BindData().RefreshData();
This type of chaining may involve extension methods. These allow addition of new methods to existing classes (even those that you don't have the source code for).
e.g.
public static class StringExtender
{
public static string MyMethod1(this string Input)
{
return ...
}
public static string MyMethod2(this string Input)
{
return ...
}
}
....
public string AString = "some string";
public string NewString = AString.MyMethod1().MyMethod2();
This can be done using extension methods
public class FirstClass
{
}
public class SecondClass
{
}
public class ThridClass
{
}
public static class Extensions
{
public static SecondClass GetSecondClass(this FirstClass f)
{
return new SecondClass();
}
public static ThridClass GetThridClass(this SecondClass s)
{
return new ThridClass();
}
}
}
AND then you can ues
FirstClass f= new FirstClass();
f.GetSecondClass().GetThridClass();

return type in C#

I have two classes named ROAD and PATH
public class ROAD
{
public string getData()
{
return "Marlton Road";
}
}
public class PATH
{
public string getData()
{
return "Tagore Path";
}
}
Also i have a function named FETCH() in my Static Void Main
FETCH() contains following code
public returnType FETCH(bool flag)
{
if(flag)
{
ROAD obj=new ROAD();
return obj;
}
else
{
PATH obj=new PATH();
return obj;
}
}
Now my question is what should be the return type of function FETCH().
Or is there any other way to implement this logic.
It would have to be object in this case, as PATH and ROAD have no common base type. (They also don't follow .NET naming conventions - something which should be fixed, along with your getData method, and your FETCH method. Even in sample code, it's worth trying to make your names follow the normal conventions).
Consider making the two classes implement an interface or give them a common base class. That common type could then be the return type of the method. It looks like you could probably have an interface with your getData method in, for example. Hopefully in your real classes it could have a more meaningful name - something to do with both paths and roads.
I suggest you create an interface that both PATH and ROAD implement (e.g. IGetData) then have both classes implement it, and have FETCH return an IGetData.
Object, and then you cast to ROAD or PATH. Or, if they share a common base class, return that. See also.
But you probably don't want to do this. ROAD and PATH should each have their own static factory method:
class ROAD {
static ROAD newRoad() { return new ROAD(); }
}
class PATH {
static PATH newPath() { return new PATH(); }
}
Or some other, better pattern, depending on why you're doing it this way.
using interface would be the best way:
public interface IData
{
string getData();
}
public class ROAD : IData
{
public string getData()
{
return "Marlton Road";
}
}
public class PATH : IData
{
public string getData()
{
return "Tagore Path";
}
}
public IData FETCH(bool flag)
{
if (flag)
{
ROAD obj = new ROAD();
return obj;
}
else
{
PATH obj = new PATH();
return obj;
}
}
How about this:
interface IWithData
{
string GetData();
}
class Path: IWithData
{
public string GetData()
{
return "Tagore Path";
}
}
class Road: IWithData
{
public string GetData()
{
return "Marlton Road";
}
}
class SomeOtherClass
{
// ...
public IWithData FETCH(bool flag)
{
if(flag)
{
Road obj=new Road();
return obj;
}
else
{
Path obj=new Path();
return obj;
}
}
// ...
}
It's object. If you want it to be something else, you just have to have those classes share a common base or implement a common interface. For example:
public class Road : IPavedSurface
{
// members
}
public class Path : IPavedSurface
{
// members
}
// then
public IPavedSurface Fetch(bool flag)
{

Categories

Resources