avatarShahzad Aslam

Summary

The provided web content discusses anonymous methods in C#, explaining their syntax, usage with examples, and limitations.

Abstract

Anonymous methods in C# are methods without names introduced in C# 2.0, allowing developers to define methods inline for purposes such as event handling or LINQ queries. These methods are particularly useful when a method is required as a delegate parameter. The content includes examples demonstrating how to declare and use anonymous methods, including the use of outer variables. It also outlines several limitations of anonymous methods, such as the inability to access ref or out parameters, contain jump statements, specify access modifiers, or be asynchronous. Additionally, the content emphasizes that anonymous methods cannot access unsafe code and do not support expression body syntax, which is available in lambda expressions.

Opinions

  • The author suggests that anonymous methods are particularly useful for event handling and LINQ queries, implying that they can lead to more concise and readable code in these contexts.
  • The author points out that anonymous methods are a feature that enhances the flexibility of C# programming by allowing inline method definitions.
  • The limitations of anonymous methods are presented as drawbacks that may affect their applicability in certain scenarios, such as when asynchronous operations or unsafe code is involved.
  • The comparison between anonymous methods and lambda expressions indicates that while both serve similar purposes, lambda expressions offer additional features like asynchronous functionality and expression body syntax.
  • The encouragement to clap and follow the author suggests that the author values reader engagement and feedback on the content provided.

Anonymous Method in C# with Examples

An anonymous method is a method which doesn’t contain any name which is introduced in C# 2.0. In C#, an anonymous method allows you to define a method inline without explicitly declaring a separate named method. It’s particularly useful when you need a method as a delegate parameter, such as for event handling or LINQ queries.

Anonymous Method in C# with Examples

Here’s a basic syntax of an anonymous method:

Here’s how you declare and use interfaces in C#.

Example

// An Anonymous Method

delegate(parameters) {
  // method body
};

For example, to create an anonymous method that wrapped a fruit name and assign it to a delegate:

Example

using System;

// Define a delegate
delegate void fruitName(string name);

public class Program
{
  public static void Main(string[] arge)
  {
    // Create an anonymous method and assign it to a delegate
    fruitName fruit = delegate(string name)
    {
        Console.WriteLine("My favorite fruit is: {0}", name);
    };
    fruit("Cherry");
  }
}

Output

My favorite fruit is: Cherry

In above example:

  1. delegate string fruitName(string name); declares a delegate named fruitName that takes an string parameter and display a fruit name string.

2. fruit is assigned an anonymous method that takes an string name and display a fruit name string.

3. fruit(“Cherry”); demonstrates calling the delegate with an argument Cherry, which prints My favorite fruit is: Cherry.

Create anonymous method with Outer variables

using System;

// Define a delegate
delegate void fruitName(string name);

public class Program
{
  public static void Main(string[] arge)
  {
    string like = "Kiwi";
    // Create an anonymous method and assign it to a delegate
    fruitName fruit = delegate(string name)
    {
      Console.WriteLine("My favorite fruit is: {0}", name);
      // Accessing outer aariable in anonymous method
      Console.WriteLine("I Like {0} also", like);
    };
    fruit("Cherry");
  }
}

Output

My favorite fruit is: Cherry
I Like Kiwi also
  1. delegate string fruitName(string name); declares a delegate named fruitName that takes an string parameter and display a string.

2. fruit is assigned an anonymous method that takes an string name and display a fruit name string.

3. fruit(“Cherry”); demonstrates calling the delegate with an argument Cherry, which prints My favorite fruit is: Cherry.

4. In this example we are accessing an variable inside anonymous method that is declared out side the anonymous method. Such type of variables is known as Outer variables. As shown in the below example like is the outer variable.

Limitation of Anonymous Method

1. Cannot Access Ref or Out Parameters:

Ref and Out,in parameters does not access in anonymous method. This restricts their ability to modify variables declared in the outer scope.

2. Cannot Contain Jump Statement

It cannot contain jump statement like goto, break or continue.

3. Cannot Specify Access Modifiers:

Anonymous methods are always private and cannot have explicit access modifiers (public, private, internal, etc.). This limits control over visibility compared to named methods.

4. Can Be Used AS Event Handler

We can also use an anonymous method as an event handler.

5. Does Not Access UnSafe Code

An anonymous method does not access unsafe code.

6. Order of Definition Doesn’t Matter:

The order in which the parts of the partial class are defined doesn’t matter. The compiler merges them together to create a single class.

7. No Asynchronous Functionality:

Anonymous methods cannot be asynchronous (async), which limits their usage in scenarios requiring asynchronous operations like tasks and async-await patterns. Lambda expressions, on the other hand, can be async.

8. No Expression Body Syntax:

Unlike lambda expressions, anonymous methods require the full method body with {} and explicit return statements.

Thanks for read.

For more useful tutorials please visit the site: C-Sharp Tutorial and also if you find useful to this article please clap and follow the author by hitting below button.

C Sharp Programming
Dotnet
Programming
Software Development
Methods
Recommended from ReadMedium