csharp

C# Anonymous Method and C# Anonymous Type with examples

C# Anonymous methods

C# Anonymous method and C# Anonymous Type:- Anonymous method provides a technique to pass a code block as a delegate parameter. You can use anonymous methods instead of defining event handler methods. C# Anonymous method is a method that does not actually exist as a method in the traditional sense, i.e. it is not a method of any particular class. Instead, an anonymous method is created solely for use as a target for the delegate.


General Syntax of  C#Anonymous Method:

To create an C# Anonymous method, you need the following code:

the parameter is a list of parameters matching those of the delegate type.

Example: how to use simple Delegate Anonymous Method in C#:

Output:

C# Anonymous Method

C# version 2 introduced C# anonymous methods: instead of creating a processing function and associating it with an event, as it was supposed to be in versions 1 and 1.1, and like this can still be done in version 2 (example here of the processing of the click on a button in programming Windows with bB as internal name):



We have seen that it is now possible to write:

But we can now also write, avoiding having to explicitly create a function of treatment :

It is possible to declare variables inside the delegate. The variables are then local to the delegate. With this last syntax, however, it is not possible to perform – = on the event (to end processing). However, we have access to the variables of the function in which this last line is found as well as to the fields of the class, which constitutes the main interest of the technique.

 The notion of closure in C# Anonymous Method:

C# Anonymous methods implement what is called closing (or more commonly closure, in English). Anonymous functions capture variables from their environment function. Consider the following example:

The C# Anonymous method was declared in function f. This has two local variables, X and Y. Normally, the local variables to the functions are destroyed (their memory space is freed) at the end of the function.

But the C# Anonymous method makes use of X. The instructions for this C# Anonymous method will be executed following a click on the button, long after the exit of f! C# imagined a mechanism (even if this one is borrowed from languages ​​that indulge in confidentiality) that makes this possible: variables local to the function that is used in the method anonymous (this is the case with X but not Y) are captured. The compiler creates a special data area for these variables and this area survives function f. The variables captured are stored in this area. To show the effect, let’s create a function f that starts five threads, in other words, five executions parallels of the same part of code:


Example: how to use threads in c# anonymous method:

Output:

C# Anonymous Method

The variable X has therefore been placed in a memory area that survives f. During each execution of the anonymous method, X accesses this area.


C# Anonymous types:

The C# Anonymous type mechanism in C# allows you to automatically declare a tuple type using a simple syntax. Tuple type is a type that contains a collection of properties that are related in some way to each other. In the first line of the following code, I define a class with two properties (Name of type String and Year of type Int32), I create an instance of this type and set the Name property to Fawad khan and the Year property to 1994.

A C# Anonymous type is created here because no name type was defined after the words new, thus, the compiler automatically creates the type name, but does not tell what it is (therefore, the type is called anonymous). Using syntax object initialization.

So, I, as a developer, have no idea about the type name at compile time and I don’t know which type variable o1 was declared. However, there is no problem here – I can use the mechanism for implicit typing of a local variable, so that the compiler can determine the type by the expression on the right side of the statement assignment (=).

So let’s see what the compiler really does. Note to the following code:

When you write this code, the compiler determines the type of each expression, creates private fields of these types, for each type of field creates public properties is read-only and creates a constructor for all of these expressions. The constructor code initializes the private read-only fields by evaluating the resulting values. In addition to this, the compiler overrides the Equals, GetHashCode and ToString methods of the object and generates the code inside all these methods. The compiler generated class looks like this:

The compiler generates Equals and GetHashCode methods so that instances of the C# Anonymous type can be stored in hash tables. Immutable properties, in contrast from properties for reading and writing, help to protect the hashcode of an object from changes.


Changing the hashcode of an object used as a key in a hash table can prevent the object from being found. The compiler generates a ToString method for simplify debugging. In the Visual Studio debugger, you can hover your mouse over the variable associated with the anonymous type instance and Visual Studio will call method ToString and will show the resulting string in the tooltip window. By the way, The IntelliSense window in Visual Studio will suggest property names as you code in the editor – a very useful feature.

The compiler supports two additional syntaxes for declaring a property inside a C# Anonymous type, where variables are used to define property names and types:

In this example, the compiler determines that the first property should be named Name. Since Name is the name of a local variable, the compiler sets the value of the property type to the same type as the local variable, that is, String. For the second property, the compiler uses the field/property name: Year. Year is an Int32 property of the DateTime class, and therefore a property Year in the C# Anonymous type will be of type Int32. When the compiler creates an instance of an C# Anonymous type, it assigns a property to the Name instance with the same value as the local variable Name, so that the Name property will be bound with the line Grant. The compiler will assign the same value to the property of the Year instance, which is the return value from the dt property of the Year.

The compiler is very clever about figuring out the C# Anonymous type. If the compiler sees that you have defined many C# Anonymous types with identical structures, then it creates one definition for a C# Anonymous type and many instances of this type. By the same structure, I mean that the C# Anonymous types have the same type and name for each property and that these properties are defined in the same order. In the code from the above example, the type of the variable o1 and the type variable o2 is the same, since two lines of code define an anonymous type with property Name / String and Year / Int32, and Name comes before Year.

Since two variables are of the same type, a lot of useful possibilities open up – for example, to check if two objects contain the same values, and assign a reference to one object to a variable of another object:

Since these types are identical, then you can create an array of explicit types from C# Anonymous types:



C# Anonymous types are commonly used with integrated language technology queries (Language Integrated Query, LINQ), when the query results in a collection of objects of the same C# Anonymous type, after what is the processing of objects in the resulting collection. All this is done in one method. In the following example, all files from the folder with my documents, which have changed in the last seven days:

Instances of C# Anonymous type must not extend outside the method. The method prototype cannot contain a parameter of a C# Anonymous type, because set an anonymous type is not possible. By the same principle, a method cannot return a C# Anonymous type reference. Although an instance of an anonymous type can be interpreted as Object (all C# Anonymous types derive from Object), it is not possible to convert a variable of type Object back to an anonymous type, because the name of the C# Anonymous type is unknown at compile time. For transmission tuple type should use the System.Tuple type.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button