How to make inline functions in C #

I am using Linq To XML

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

but I want to do some calculations for the prefix before adding it to xml, for example, excluding spaces, special characters, some calculations, etc.

I do not want to create functions, because they will not help in any other part of my program, but it is, and is there a way to create built-in functions?

+54
c #
Feb 04 '11 at 16:03
source share
4 answers

Yes, C # supports this. Several syntaxes are 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) { Console.WriteLine(x); } Action<int> helloWorld = delegate // parameters can be elided if ignored { Console.WriteLine("Hello world!"); } 
  • Lambdas expression (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 
  • Lambdas statement (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 two different types for them: Func and Action . Func return values, but no Action . The final type of the Func parameter is the return type; all others are parameters.

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 

They can be called directly, as if they were the usual 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. 
+124
Feb 04 '11 at 16:11
source share

Yes.

You can create anonymous methods or lambda expressions :

 Func<string, string> PrefixTrimmer = delegate(string x) { return x ?? ""; }; Func<string, string> PrefixTrimmer = x => x ?? ""; 
+15
04 Feb 2018-11-11T00:
source share

The answer to your question is yes and no, depending on what you mean by a “built-in function”. If you use the term as it is used in C ++ development, then the answer will be negative, you cannot do this - even a lambda expression is a function call. Although it is true that you can define inline lambda expressions to replace function declarations in C #, the compiler still finishes creating an anonymous function.

Here is some really simple code I used to test this (VS2015):

  static void Main(string[] args) { Func<int, int> incr = a => a + 1; Console.WriteLine($"P1 = {incr(5)}"); } 

What does the compiler generate? I used a great tool called ILSpy that displays the generated IL assembly. Take a look (I have omitted a lot of things to set up the class)

This is the main function:

  IL_001f: stloc.0 IL_0020: ldstr "P1 = {0}" IL_0025: ldloc.0 IL_0026: ldc.i4.5 IL_0027: callvirt instance !1 class [mscorlib]System.Func`2<int32, int32>::Invoke(!0) IL_002c: box [mscorlib]System.Int32 IL_0031: call string [mscorlib]System.String::Format(string, object) IL_0036: call void [mscorlib]System.Console::WriteLine(string) IL_003b: ret 

See lines IL_0026 and IL_0027? These two instructions load number 5 and call the function. Then enter IL_0031 and IL_0036 and print the result.

And here is a function called:

  .method assembly hidebysig instance int32 '<Main>b__0_0' ( int32 a ) cil managed { // Method begins at RVA 0x20ac // Code size 4 (0x4) .maxstack 8 IL_0000: ldarg.1 IL_0001: ldc.i4.1 IL_0002: add IL_0003: ret } // end of method '<>c'::'<Main>b__0_0' 

This is a really short function, but it is a function.

Is it really worth the effort to optimize? Nope. Maybe if you call it thousands of times per second, but if performance is important, you should consider invoking your own C / C ++ code to do the job.

In my experience, readability and maintainability are almost always more important than optimizing for a few microseconds in speed. Use functions to make your code readable and control the scope of variables and not worry about performance.

"Premature optimization is the root of all evil (or at least most) programming." - Donald Knut

"A program that does not work correctly does not require a quick start" - Me

+6
Dec 01 '16 at 0:02
source share

You can use Func , which encapsulates a method with one parameter and returns the value of the type specified by the TResult parameter.

 void Method() { Func<string,string> inlineFunction = source => { // add your functionality here return source ; }; // call the inline function inlineFunction("prefix"); } 
+5
Feb 04 '11 at 16:07
source share



All Articles