(Lambda function may or may not be what I'm looking for, I'm not sure)
Essentially what I'm trying to accomplish is this:
int areaOfRectangle = (int x, int y) => {return x * y;};
but it gives error: "Cannot convert lambda expression to type 'int' because it is not a delegate type"
The more detailed problem (that really has nothing to do with the question, but I know someone will ask) is:
I have several functions that branch from an overridden OnLayout and several more functions that each of those depend on. For readability and to set precedent for later expansion, I want the functions that branch from OnLayout to all look similar. To do that, I need to compartmentalize them and reuse naming as much as possible:
protected override void OnLayout(LayoutEventArgs levent)
switch (LayoutShape)
{
case (square):
doSquareLayout();
break;
case (round):
doRoundLayout();
break;
etc..
etc..
}
void doSquareLayout()
{
Region layerShape = (int Layer) =>
{
//do some calculation
return new Region(Math.Ceiling(Math.Sqrt(ItemCount)));
}
int gradientAngle = (int itemIndex) =>
{
//do some calculation
return ret;
}
//Common-ish layout code that uses layerShape and gradientAngle goes here
}
void doRoundLayout()
{
Region layerShape = (int Layer) =>
{
//Do some calculation
GraphicsPath shape = new GraphicsPath();
shape.AddEllipse(0, 0, Width, Height);
return new Region(shape);
}
int gradientAngle = (int itemIndex) =>
{
//do some calculation
return ret;
}
//Common-ish layout code that uses layerShape and gradientAngle goes here
}
All the examples I find right now say you have to declare a delegate but I know I've seen a one liner lambda declaration...
Try like this;
Check
Func<T1, T2, TResult>
from MSDN;Try
Func<int, int, int> areaOfRectangle = (int x, int y) => { return x * y;};
instead.Func
works as as delegateLook here for more info on lamda expression usage
This answer is also related and has some good info
If you're doing it for readability and are going to reproduce the same functions
layerShape
andgradientAngle
, you might want to have explicit delegates for those functions to show they are in fact the same. Just a thought.You're close:
So for your specific case your declaration would be:
The variable type is based on your parameters and return type: