Anonymous Functions in C#
18:19Introduction
In this post I'm going to explain about Anonymous Functions in C#Anonymous functions
In C# 1.0 you can use a delegate and pass a function reference with an initializing delegate with a function name, but C# 2.0 introduced anonymous functions.Anonymous function is a inline function or expression that a delegate is using.
Example
Creating an anonymous function as an inline block of code to be passed as a delegate parameter. Please see below:using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Anonymous { class SimpleAnonymous { public delegate void delegateAnon(); static void Main(string[] args) { delegateAnon obj = delegate() { Console.WriteLine( "Simple Anonymous"); }; obj(); } } }
Use of an anonymous function can reduce the lines of code. So, here in the program above you can see I just passed a block of code for a delegate parameter inside of creating a function anywhere else and passing the function name. The anonymous function uses the delegate keyword while delegate initialization writes a block of code. You can also pass a parameter for an anonymous function as follows:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Anonymous { class AnonymousParam { public delegate void delegateAnon( string Mesg); static void Main(string[] args) { delegateAnon obj = delegate(string Mesg) { Console.WriteLine(Mesg); }; obj("AnonymousParam"); } } }
0 comments