• Nenhum resultado encontrado

Abstract Concepts in C# – using Delegates

N/A
N/A
Protected

Academic year: 2017

Share "Abstract Concepts in C# – using Delegates"

Copied!
6
0
0

Texto

(1)

Annals of “Dunarea de Jos” University of Galati Fascicle I. Economics and Applied Informatics

Years XXI – no2/2015

ISSN-L 1584-0409 ISSN-Online 2344-441X www.eia.feaa.ugal.ro

Abstract Concepts in C# – using Delegates

Adrian LUPASC

A R T I C L E I N F O A B S T R A C T

Article history:

Accepted September Available online September

JEL Classification

C , D , L

Keywords:

C#,Delegate, Object delegate, Multicasting delegate, Type-safe

function pointer

Many developers, especially beginners, often find it difficult to realize and understand the benefits and advantages of using abstract concepts specific to the C# language, like delegates. C# doesn't help matters by allowing us to declare field-like events which are automatically backed by a delegate variable at the same name. Another source of confusion is due to the overloading of the term delegate . Sometimes it is used to mean a delegate type, in other cases it can be used to mean an instance of a delegate type. We shall use delegate type and delegate instance to distinguish between them, and delegate when we are talking about the whole topic in a general sense. )n this context, the present paper aims to clarify all these aspects related to the use of delegate in the specific context, providing concrete examples in this respect. Moreover, this paper presents the main benefits of using delegates in C# language.

© EA). All rights reserved.

1. Introduction

C# is a free application development environment produced by Microsoft. )t is an )DE Integrated

Development Environment and provides a set of tools, including an editor program code for writing C#

compiler, debugger, compiler tools for process automation, and more. C# is a programming environment that

performs automatic memory management due to integration on the .NET platform. Today, no matter what

domain of activity is taken into consideration, the information systems are considered to be essential, because they significantly reduce the effort associated with the human factor of an entity, and also improves and simplifies considerably the activity flows. )n this sense, if we want to develop a complex application, we must use all these concepts that are specific to that programming language.

C# is today perhaps one of the most used languages for creating applications for Microsoft, being regarded as a Microsoft version of Java. We can consider this as true, but up to a point; the basics are quite similar and there are many concepts introduced by Java which were taken from C#. (owever, this is not just a copy of Java language or an alternative that offers exactly the same features.

There are many technologies that use C# because with the help of this software, we can develop applications that can run on ordinary computers, tablets or phones. Alternatively it is possible to use other languages as well, like everything connected with mobile applications, as Windows is written basically in C# language.

Nevertheless, if we want to get all benefits from an information system, it is important to efficiently use every available resource at the computer system level. Therefore, the design and implementation of an information system should be done by taking into account all important concepts that depend on the efficient use of a computer system resources. )n this context, this paper aims to present the main aspects related to the use of abstract concepts in C#, namely delegates.

(2)

Usually, delegates are objects that know how to call a method. The delegations are reference types that are designed to maintain a list of methods with the same signature and then call them all at once. A delegate is a type-safe function pointer it holds a reference pointer to a function . The signature of the delegates must match the signature of the function, the delegate points too, otherwise we get a compiler error. This is the reason delegates are called type-safe function pointers.

The delegations are declared outside classes globally . What is important about it is that they have no body and basically, by declaring a delegation, it incorporates the specified signature methods. )t is important to specify that the delegate keyword doesn't always mean that a delegate type is being declared. The same keyword can be used when creating instances of the delegate type using anonymous methods

http://csharpindepth.com/Articles/Chapter /Events.aspx .

Delegates are widely used in events declaration and are useful to offer to the user of our objects some ability to customize their behavior. Most of the time, we can use other ways to achieve the same purpose and we don t believe that the user can be forced to create delegates. )t is just the easiest way in some situations to get the thing done.

Delegate is a type which holds the method reference in an object. )t is also referred to as a type-safe function pointer. There is some advantage of delegates: encapsulating the method's call from caller, effective use of delegate improves the performance of an application and used to call a method asynchronously

http://www.tutorialspoint.com/csharp/csharp_delegates.htm .

3. Define Delegates

A delegate is similar to a class. We can create an instance of it and when we do so, we pass in the function name as a parameter to the delegate constructor and it is to this function the delegate will point to. Delegate s syntax look very much similar to a method, except they have the delegate modifier, are terminated with a semi-colon ; and have no implementation. Below ) presented the way to define a delegate:

access_modifier delegate returnType delegateName (listOfDelegateParameters);

Return type and listOfDelegateParameters define the signature of the delegate. Any object of the delegate

allows developers to encapsulate a reference to a method. We can assign any method to a delegate object, having the same signature as that of the delegate. For instance, in the following example, we have a simple declaration of delegate with three parameters:

public delegate int my_delegate (string delegatePar1, int delegatePar2, myClass delegatePar3);

)n our code, we can use delegates with, or without parameters list and we should follow the same

syntax as in the method. )f we are referring to the method with two int parameters and int return type, the

delegate which are declaring should be in the same format. This is why it is referred to as type-safe function pointer.

The fundamental points of data in any delegate instance are the method the delegate refers to, and a

reference to call the method on; for static methods, no target is required. The CLR Common Language

Runtime itself supports other slightly different forms of delegate, where either the first argument passed to a

static method is held within the delegate, or the target of an instance method is provided as an argument when the method is called.

A delegate is a reference to a method; whereas objects can be sent as parameters into methods, constructor or whatever, methods are a bit trickier. But every once in a while we might feel the need to send a method as a parameter to another one, and then we need delegates. Delegates are most useful when wanting to declare a blocks of code that we want to pass around or when we want to do late evaluation of code blocks, like a function where we have some transform action, and want to have a before transform and an after transform action that we can evaluate within our transform function, without having to know whether the begin transform is filled, or what it has to transform. Also, delegates are useful when we create event handlers; we do not want to evaluate the code now, but only when needed, so we register a delegate that can be invoked when the event occurs.

(3)
(4)

A fundamental feature of delegates is that they combine a method pointer with an object that is of a type proper for use with that method. The invoker of a delegate does not need to care what the delegate's object is; it is guaranteed to be the right type for the object. Also, we can consider delegates to be anonymous interfaces because in many cases we can use them whenever we need an interface with a single method, but we do not want the overhead of defining that interface.

4. Benefits and advantages of using delegates

Delegates represent a simple way of encapsulating program code. For example, when we attach an event handler to the button, that handler is a delegate. The button does not need to know what it does, just how to call it at the right time. Also, another example is L)NQ – filtering, projecting etc. which requires the same kind of template code. With lambda expressions in C# which are converted into delegates or expression trees this makes it really simple:

var studName = student.Where(stud => stud.Age >= 18).Select(stud => stud.Name);

Another ways of using a delegate is as a single-method interface type or refers to the use of delegates in design: which can lead to easy reuse of code, can provide a great amount of flexibility in our designs and allow us to develop libraries and classes that can be extensible, since it provides an easy way to hook in other functionality.

Delegates provide additional level of abstraction, because we can abstract out some action expressed in the code and pass is as a parameter in some other method, like any other parameter. Object oriented programming virtual methods does something like that, but delegates has no limitations: delegate instances can accept any method in its invocation list; if the method has matching signature it can be virtual or not, static or instance method, of the same class or any other which is the most important difference between a delegate and a virtual method .

5. Combining delegates

A useful property of delegate objects is that more objects can be assigned to another delegate instance by using the + operator. )t is important to mention that only delegates of the same type can be combined; delegates can be combined such that when you call the delegate, a whole list of methods are called

– potentially with different targets https://msdn.microsoft.com/en-us/library/ms .aspx . Combined

delegates can themselves be combined together, effectively creating one big list of simple delegates. A delegate can call more than one method when invoked. This is referred to as multicasting. To add an extra method to the delegate's list of methods, simply requires adding two delegates using the addition or addition assignment operators.

MethodClass myObj = new MethodClass(); Del myDel1 = myObj.method1;

Del myDel2 = myObj.method2; Del myDel3 = delMth;

Del allMthsDel = d1 + d2;

)n the above code, allMthsDel contains three methods in its invocation list—method1, method2, and

delMth. The three delegates: myDel1, myDel2 and myDel3 remain unchanged. When allMthsDel is invoked, all

the three methods are called. )f the delegate uses reference parameters, the reference is passed sequentially to each of the three methods in turn, and any changes by one method are visible to the next method.

(5)

Figure no.2 – Combining delegates – result window

)n the example shown above, two static void type functions were created: thus the first function

displays Hello text followed by txt1 string value taken as formal parameter of the mthHello function and the

second one displays the txt2 string value taken as formal parameter of the mthText function followed by

you are using delegates in C#!!! . )n fact, txt1 and txt2 represents values passed as parameters by the

(6)

invokes one or more methods through the delegate instance and are used to handle multiple methods on a single event, to define asynchronous methods, for decoupling and implementing generic behaviors. Also, combining delegate can be used to invoke the multiple methods.

References

1. Clark Dan, Beginning C# Object – Oriented Programming, Apress Publishing, 2011.

2. Hilyard Jay, Teilhet Stephen, C# 6.0 Cookbook, 4th Edition, O'Reilly Media, Inc. Publishing, 2015. 3. Kendal Simon, Object Oriented Programming using C#, Simon Kendal & Ventus Publishing Aps, 2011.

4. Kieran Mulchrone, An Introduction to Object Oriented Programming with C#, September 2010 (http://euclid.ucc.ie/pages/staff/mulchrone/am6007.pdf).

5. Olsson Mikael, C# Quick Syntax Reference, Apress Publishing, 2010. 6. Schilldt Herbert, C# 3.0: A beginner’s Guide, McGraw Hill Publishing, 2009.

7. Troelsen Andrew, Japikse Philip, C# 6.0 and the .NET 4.6 Framework, Seventh Edition, Apress Publishing, 2015. 8. http://stackoverflow.com/questions/2019402/when-why-to-use-delegates

9. http://csharpindepth.com/Articles/Chapter2/Events.aspx 10. https://msdn.microsoft.com/en-us/library/ms173171.aspx 11. http://www.tutorialspoint.com/csharp/pdf/csharp_delegates.pdf

Imagem

Figure no.2 – Combining delegates – result window

Referências

Documentos relacionados

The main clause is clause (1): if the object’s fields have type F and its session type allows a certain method to be called, then it means that the method body is typable with

A mais conhecida delas talvez seja aquela onde Kierkegaard está no centro do universo e todas as demais coisas gravitam ao seu redor, o periódico aponta que

The sampling cloth technique is a reference method  for stink bug monitoring and is considered a nonbiased  method  to  estimate  pest  population  (Kogan 

The Generalized Finite Element Method GFEM is a Partition of Unity PoU based Galerkin method, according to which the basic approximation space provided by a PoU

Though the sensitivity of method C is less when compared to method A and method B, the OFX-iron(III) complex in sulphuric acid medium has suitable characteristics for

Although the intensity method (method A) does not provide the best estimate of cellulose crystallinity, this method presented the best regression model and is also the

Background: Planimetry is a method used to evaluate the progression of skin wound healing. Computerized planimetry is still an experimental method, but its advantages have

Estas passam por um poder de análise avançado (elevada competência no que diz respeito à interação com os dados de forma a trabalhar com inteligência artificial), gestão