I\'m using Linq To XML
new XElement(\"Prefix\", Prefix == null ? \"\" : Prefix)
but I want to do some computation to the prefix before addi
Yes, C# supports that. There are several syntaxes available.
Anonymous methods were added in C# 2.0:
Func add = delegate(int x, int y)
{
return x + y;
};
Action print = delegate(int x)
{
Console.WriteLine(x);
}
Action helloWorld = delegate // parameters can be elided if ignored
{
Console.WriteLine("Hello world!");
}
Lambdas are new in C# 3.0 and come in two flavours.
Expression lambdas:
Func add = (int x, int y) => x + y; // or...
Func add = (x, y) => x + y; // types are inferred by the compiler
Statement lambdas:
Action print = (int x) => { Console.WriteLine(x); };
Action print = x => { Console.WriteLine(x); }; // inferred types
Func add = (x, y) => { return x + y; };
Local functions have been introduced with C# 7.0:
int add(int x, int y) => x + y;
void print(int x) { Console.WriteLine(x); }
There are basically two different types for these: Func and Action. Func
s return values but Action
s don't. The last type parameter of a Func
is the return type; all the others are the parameter types.
There are similar types with different names, but the syntax for declaring them inline is the same. An example of this is ComparisonFunc
.
Func compare1 = (l,r) => 1;
Comparison compare2 = (l, r) => 1;
Comparison compare3 = compare1; // this one only works from C# 4.0 onwards
These can be invoked directly as if they were regular methods:
int x = add(23, 17); // x == 40
print(x); // outputs 40
helloWorld(x); // helloWorld has one int parameter declared: Action
// even though it does not make any use of it.