Joe Dixon Joe Dixon - 2 months ago 21
C# Question

How to make inline functions in C#

I'm using Linq To XML

new XElement("Prefix", Prefix == null ? "" : Prefix)

but I want to do some computation to the prefix before adding it to the xml, like eliminating spaces, special chars, some calculations etc

I don't want to create functions because this ones won't be of any help on any other part of my program but this, so is there any way to create inline functions??


Yes, C# supports that. There are several syntaxes available:

  • Anonymous methods (available from C# 2 onwards)

    Func<int, int, int> add = delegate(int x, int y)
                             return x + y;
    Action<int> print = delegate(int x)
    Action<int> helloWorld = delegate // parameters can be elided if ignored
                                 Console.WriteLine("Hello world!");
  • Expression Lambdas (available from C# 3 onwards)

    Func<int, int, int> add = (int x, int y) => x + y; // or...
    Func<int, int, int> add = (x,y) => x + y; // types are inferred by the compiler
  • Statement lambdas (available from C# 3 onwards)

    Action<int> print = (int x) => { Console.WriteLine(x); };
    Action<int> print = x => { Console.WriteLine(x); }; // inferred types
    Func<int, int, int> add = (x,y) => { return x + y; };

There are basically two different types for these: Func and Action. Funcs return values but Actions 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 Comparison<T>, which is roughly equivalent to Func<T,T,int>.

Func<string,string,int> compare1 = (l,r) => 1;
Comparison<string> compare2 = (l,r) => 1;
Comparison<string> compare3 = compare1; // this one only works from C# 4 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); // helloWord has one int parameter declared: Action<int>
               // even though it does not make any use of it.