C# Tutorial

C# Tutorial C# First Application C# Variables C# Data Types C# Operators C# Keywords

C# Control Statement

C# If Statements C# Switch Statements C# for Loop C# While Loop C# do While loop C# Jump Statements C# Function C# functions with out variable

C# Arrays

C# Arrays

C# Function

C# Function call by value C# Call by reference C# Passing array to function C# Multidimensional Arrays C# Jagged Arrays C# Params C# Array Class C# Command Line Arguments

C# Object Class

C# Object and Classes C# Constructors C# Destructor C# this Keyword C# static field C# static class C# Static Constructor C# Structs C# enum C# Properties

C# Inheritance

C# Inheritance C# Multilevel Inheritance C# Aggregation C# Member overloading C# Method Overriding C# Base

C# Polymorphism

C# Polymorphism C# Sealed

C# Abstraction

C# Abstraction C# Interface

C# Namespace

C# Namespace C# Access Modifiers C# Encapsulation

C# Strings

C# String

C# Misc

C# Design Patterns Dictionary in C# Boxing and Unboxing in C# Ref and Out in C# Serialization in C# Dispose and Finalize in C# CONSOLE LOG IN C# Get File extension in C# Insert query in c# Difference Between List and Dictionary in C# Getters and Setters in C# Extension Methods in C# Insert query in c# CONSOLE LOG IN C# Get File extension in C# Random.NextDouble() Method in C# Binary Search in C# Difference between Delegates and Interfaces in C# Double.IsFinite() Method in C# Index Constructor in C# Abstraction in C# Basic OOPS Concepts In C# Queue.CopyTo() Method in C# single.compareto() method in C# C# Throw Exception in Constructor DECODE IN C# file.setlastwritetimeutc() method in C# Convert Object to List in C# convert.ToSByte(string, IFormatProvider) Method in C# C# Declare Delegate in Interface console.TreatControl C As Input property in C# Copying the queue elements to 1-D Array in C# Array.Constrainedcopy() Method in C# C# in and out Char.IsLetterOrDigit() method in C# Debugging in C# decimal.compare() method in C# Difference between Console.Read and Console.Readline in C# Metadata in C# C# Event Handler Example Default Interface Methods in C# Difference between hashtable and dictionary in C# C# program to implement IDisposable Interface Encapsulation in C# SortedList.IndexOfVaalue(Object) Method in C# Hash Maps in C# How to clear text files in C# How to Convert xls to xlsx in C# Foreach loop in C# FIFO in C# How to handle null exception in C# Type.Is Instance Of Type() Method in C# How to add data into MySQL database using C# How to use angular js in ASP net Csharp decimal.compare() method in Csharp Difference between Console.Read and Console.Readline in Csharp How to Implement Interface in Csharp char.IsUpper() Method in C# Index Of Any() Method in C# Quantifiers in C# C# program to Get Extension of a Given File C# Error Logging C# ENCRIPTION Can we create an object for Abstract Class in C# Console.CursorVisible in C# SortedDictionary Implementation in C# C# Hash Table with Examples Setting the Location of the Label in c# Collections in c# Virtual Keyword in C# Reverse of string in C# String and StringBuilder in C# Encapsulation in C# SortedList.IndexOfVaalue(Object) Method in C# Hash Maps in C# How to clear text files in C# How to Convert xls to xlsx in C# Foreach loop in C# FIFO in C# How to handle null exception in C# Type.Is Instance Of Type() Method in C# How to add data into MySQL database using C# How to use angular js in ASP net Csharp decimal.compare() method in Csharp Difference between Console.Read and Console.Readline in Csharp How to Implement Interface in Csharp char.IsUpper() Method in C# Index Of Any() Method in C# Quantifiers in C# C# program to Get Extension of a Given File Difference between ref and out in C# Singleton Class in C# Const And Readonly In Csharp BinaryReader and BinaryWriter in C# C# Attributes C# Delegates DirectoryInfo Class in C# Export and Import Excel Data in C# File Class in C# FileInfo Class in C# How to Cancel Parallel Operations in C#? Maximum Degree of Parallelism in C# Parallel Foreach Loop in C# Parallel Invoke in C# StreamReader and StreamWriter in C# TextReader and TextWriter in C# AsQueryable() in C# Basic Database Operations Using C# C# Anonymous Methods C# Events C# Generics C# Indexers C# Multidimensional Indexers C# Multithreading C# New Features C# Overloading of Indexers Difference between delegates and events in C# Operator overloading in C# Filter table in C# C# Queue with Examples C# Sortedlist With Examples C# Stack with Examples C# Unsafe Code File Handling in C# HashSet in C# with Examples List Implementation in C# SortedSet in C# with Examples C# in Depth Delegates and Events in C# Finally Block in C# How to Split String in C# Loggers in C# Nullable Types in C# REVERSE A STRING IN C# TYPE CASTING IN C# What is Generics in C# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# Atomic Methods Thread Safety and Race Conditions in C# Parallel LINQ in C# Design Principles in C# Difference Between Struct And Class In C# Difference between Abstraction and Encapsulation in C# Escape Sequence Characters in C# What is IOC in C# Multiple Catch blocks in C# Appdomain in C# Call back methods in C# Change Datetime format in C# Declare String array in C# Default Access Specifier in c# Foreach in LINQ C# How to compare two lists in C# How to Convert String to Datetime in c# How to get only Date from DateTime in C# Ispostback in asp net C# JSON OBJECT IN C# JSON STRINGIFY IN C# LAMBDA FUNCTION IN C# LINQ Lambda Expression in C# Microservices in C# MSIL IN C# Reference parameter in C# Shadowing(Method hiding) in C# Solid principles in C# Static Members in C# Task run in C# Transaction scope in C# Type Conversion in c# Unit of Work in C# Unit Test Cases in c# User Defined Exception in c# Using Keyword in C# Var Keyword in C# What is gac in C#

C# Anonymous Methods

A method without a name is known as an anonymous method, and it was first introduced in C# 2.0. It is helpful when a user wishes to build an inline method and send parameters to the anonymous method like other methods. The delegate keyword defines an anonymous method, which the user can then assign to a variable of the delegate type.

Syntax:

delegate(parameter_list){

    // Code.

};

Example:

The CODE for the following program is as follows:

using System;

class Preethi {

            public delegate void petanim(string pet);

            // Main method

            static public void Main()

            {

                        // An anonymous method with one parameter

                        petanim p = delegate(string mypet)

                        {

                                    Console.WriteLine("My favorite pet is: {0}",

                                                                                                                                                my pet);

                        };

                        p("Dog");

            }

}

OUTPUT:

The Output for the following program will be:

C# Anonymous Methods
  • Inline delegate is another name for this technique.
  •  You can build a delegate object using this method without adding additional methods.
  • The outer method's variables are accessible from this method. These variables fall under the category of outside variables.
  •  The favorite is the outside variable, as demonstrated in the example below.

Example:

The CODE for the following program is as follows:

using System;

class Preethi {

            // Create a delegate

            public delegate void petanim(string pet);

            // Main method

            static public void Main()

            {

                        string fav = "Rabbit";

                        // Anonymous method with one parameter

                        petanim p = delegate(string mypet)

                        {

                                    Console.WriteLine("My favorite pet is {0}.",

                                                                                                                                                my pet);

                                    // Accessing variable defined

                                    // outside the anonymous function

                                    Console.WriteLine("And I like {0} also.", fav);

                        };

                        p("Dog");

            }

}

OUTPUT:

The Output for the following program is as follows:

C# Anonymous Methods

Another method that accepts delegate as a parameter can receive this method as a parameter. You can remove the parameter list from anonymous methods, which enables you to turn an anonymous method into a delegate.

  • Anonymous methods do not support jump statements like goo, break, and continue.
  • The anonymous method block indicates the scope of the parameters in the anonymous method.
  • Unsafe code is not accessed by an anonymous method.
  • An anonymous method cannot access the outer scopes in, ref, and out parameters.
  • To the left of the operator, an anonymous method cannot be used.
  • A method that is anonymous can also serve as an event handler.

An anonymous method is, as its name suggests, a method without a name.

Example:

The CODE for the following program is as follows:

public delegate void Print(int value);

static void Main(string[] args)

{

    Print print = delegate(int val) {

        Console.WriteLine("Inside Anonymous method. Value: {0}", val);

    };

    print(100);

}

OUTPUT:

The Output for the following program is as follows:

Inside Anonymous method. Value: 100

Example:

The CODE for the following program is as follows:

public delegate void Print(int value);

static void Main(string[] args)

{

    int i = 10;

    Print prnt = delegate(int val) {

        val += i;

        Console.WriteLine("Anonymous method: {0}", val);

    };

    prnt(100);

}

OUTPUT:

The Output for the following program is as follows:

Anonymous method: 110

Anonymous Method Limitations:

  • Statements that leap, such as goto, break, or continue, are not permitted.
  • An outer method's ref or out argument cannot be accessed.
  • It can't access or have any unsafe code.
  • It is not permitted to utilize it after the operator is on the left.

With anonymous methods, inline code blocks can be defined in C# without explicitly declaring a named method. They are a vital feature that enables programmers to define code blocks immediately at the place of use, allowing them to write straightforward and adaptable code. In this tutorial, the specifics of anonymous methods in C# will be discussed, along with usage examples and benefits.

Syntax:

The delegate keyword, an optional argument list, an arrow (=>) token, and a code block make up the syntax of an anonymous method. The parameters that the anonymous method can accept are listed in the parameter list if one is provided. The method's actual implementation is contained in the code block.

delegate (parameters)

{

    // Code block

};

Using Scenarios:

1. Event Handlers: Anonymous methods are frequently employed as event handlers. You can create the event handler inline, directly at the point of subscription, as opposed to defining separate named methods for each event. By grouping comparable code, this method eliminates the necessity for additional method declarations and enhances code readability.

button.Click += delegate (object sender, EventArgs e)

{

    // Event handler code

};

2. Callback Functions: Anonymous methods are helpful when interacting with callback functions. For instance, rather than defining distinct named methods for the callback logic when utilizing asynchronous activities or calling other APIs. This aids in keeping a clean, simple code structure.

asyncOperation.Start(callback: delegate (string result)

{

    // Callback logic

});

3. LINQ Queries: Data can be accessed from various sources, including collections, databases, and XML, using LINQ (Language Integrated Query). LINQ expressions frequently employ anonymous methods to specify unique ordering, filtering, and projection logic.

var filteredItems = items.Where(delegate (Item item)

{

    // Filtering logic

    return item.Price > 100;

});

Benefits:

1. Readability and Maintainability: Developers can write code inline, near the point of use, using anonymous methods, which improves the readability and maintainability of the code. It does away with the requirement for dispersed named methods, resulting in smaller and more self-contained code.

2. Encapsulation: Variables in the enclosing scope are accessible to anonymous methods. Closure, which increases code modularity and eliminates the need for global variables, enables you to encapsulate related data inside the anonymous procedure.

3. Conciseness: Anonymous methods lessen the verbosity of the code by eliminating the requirement to declare named methods separately. Code becomes shorter and more expressive as a result, which makes it simpler to comprehend and debug.

4. Flexibility: The ability to construct ad hoc code blocks with unique logic suited to specific contexts is made possible by anonymous methods. They are accommodating when creating distinct named methods would be tedious or superfluous.

Limitations:

While anonymous methods have many benefits, there are some drawbacks to be aware of:

1. Lack of Reusability: Because anonymous methods are defined inline, the codebase cannot use them more than once. Using named methods or lambda expressions is preferable if you reuse the same logic across several contexts.

2. Limited Functionality: Anonymous methods cannot be explicitly assigned to variables or utilized as return values. It would help if you thought about utilizing lambda expressions or named methods in their place to achieve this behavior.

Conclusion:

As a result, developers can build inline code blocks in C# by using anonymous methods, a strong and clear feature that eliminates the need for distinct named methods. They provide several advantages, such as better code readability, data encapsulation, and adaptability in situations like event handling, callbacks, and LINQ queries. Anonymous methods make code easier to read and maintain by removing the need for sporadic method declarations.

The drawbacks of anonymous methods must be considered, such as their lack of reusability and restricted functionality compared to named methods or lambda expressions. Developers should carefully analyze their use cases and select the best approach based on the needs of their application to make the best use of anonymous methods.

In conclusion, anonymous methods are a valuable tool for C# developers, offering a practical approach to managing inline code blocks and assisting in creating more concise and expressive code. They can significantly improve the overall development process and the codebase's maintainability when used wisely and in conjunction with other language features.

In C#, anonymous methods are a helpful feature that lets you build inline code blocks without declaring individual named methods. They increase the code's adaptability, readability, and maintainability, especially when event management, callbacks, and LINQ queries are included. It's vital to be aware of their limits and to decide which approach will work best for your application depending on its specific requirements.