Coding Schools


 
Python | C Sharp | Azure AI | HTML | JavaScript | CSS | SQL Server
OOPS in C#
C# Data Types
Boxing and Unboxing in C#
Garbage Collection in C#
C# - Conditional Statements
C# - Loops
Interfaces in C#
Generics in C#
Collections in C#
C# 8.0 new features
C# Singleton Design Pattern
C# Factory Design Pattern
LINQ in C#
C# - Program to Find Prime Numbers
C# - Fibonacci Sequence
C# - Factorial of a number
C# - Recursive methods
C# - Anonymous Methods
C# - String Methods
C# TDD - XUnit
C# TDD - NUnit
C# Multiton Design Pattern
C# Facade Design Pattern
C# Abstract Factory Design Pattern
C# Decorator Design Pattern
C# Composite Design Pattern

C# - Anonymous Methods



In C#, an anonymous method is a method that has no name and can be defined using the delegate keyword. Anonymous methods enable you to write inline code blocks where delegates are expected. This can simplify your code by reducing the need for small, named methods that are only used in one place. Anonymous methods were introduced in C# 2.0, and they have been largely superseded by lambda expressions in later versions of C#.

Here's an example of an anonymous method in C#:

csharp
// Delegate declaration
delegate void PrintDelegate(string msg);

class Program
{
    static void Main()
    {
        // Using an anonymous method
        PrintDelegate print = delegate(string msg)
        {
            Console.WriteLine(msg);
        };

        // Calling the anonymous method
        print("Hello, World!");
    }
}

In this example, print is a delegate of type PrintDelegate that takes a string as a parameter. The delegate is assigned an anonymous method, which simply prints the passed string to the console.

Anonymous methods were a precursor to lambda expressions, which provide a more concise syntax and are more commonly used in modern C#. Here's how the same example would look using a lambda expression:

csharp
class Program
{
    static void Main()
    {
        // Using a lambda expression
        Action<string> print = msg => Console.WriteLine(msg);

        // Calling the lambda expression
        print("Hello, World!");
    }
}

Both anonymous methods and lambda expressions have their usages, but lambda expressions are preferred for their concise syntax and capabilities. Would you like to dive deeper into delegates and lambda expressions or perhaps see more examples?




All rights reserved | Privacy Policy | Sitemap