Reputation: 10557
I'm amazed I couldn't find an answer to this question on stackoverflow or MSDN. I strongly suspect my search skills are the gap here, but I'll risk asking anyways. I've looked at these three posts here on stackoverflow. None of them are directly questions or answers to what I'm asking, but they are tangentially related enough that I hoped to glean answers from them anyways. But no luck! Anyways, here's the question!
When I define an interface which declares an Action<int, int>
property
public interface ICoordinateProcessor {
System.Action<int, int> onTwoIntegers { get; }
}
It can easily be implemented with a null-returning lambda taking two integers as parameters
public class RealCoordinateProcessor : ICoordinateProcessor {
public override Action<int, int> onTwoIntegers {
get {
return (x, y) => this.someInternalState = x + y;
}
}
}
Easy peasy! But when I use roslyn to autocomplete the interface, it fills in the following:
public class RealCoordinateProcessor : ICoordinateProcessor {
public override Action<int, int> onTwoIntegers => throw new NotImplementedException();
}
That compiles with no errors or warnings, and is also very concise syntax that I have never seen and would prefer to use. How do I use that much tighter syntax to have the same effect as my second snippet above?
Or equivalently, how do I access the parameters of the lambda in that third snippet? When I try this:
public override Action<int, int> onTwoIntegers (x, y) => throw new NotImplementedException();
The compiler freaks out because I obviously don't know what I'm doing. But I'm not sure what else to try, and I'm not sure how to search for examples.
Upvotes: 0
Views: 41
Reputation:
Now, in C#6 with Roslyn you can use Expression Bodied Function Members:
public override Action<int,int> onTwoIntegers => (x,y) => { };
In generally, it's not so much different with delegate-lambda syntax:
var onTwoIntegersClass = new RealCoordinateProcessor().onTwoIntegers;
Action<int,int> onTwoIntegersVar = (x,y)=>{};
Delegate.Combine(onTwoIntegersVar, onTwoIntegersClass);
Upvotes: 5