Spot the web RSS 2.0
# Monday, March 10, 2008

This article discusses the delegate type and how it can be used to point to methods in the application which can be invoked at later time. This article demonstrates also the delegate ability to multicast and delegate covariance.

A delegate is a type-safe object that can point to another method (or possibly multiple methods) in the application, which can be invoked at later time.

Delegates also can invoke methods Asynchronously.

A delegate type maintains three important pices of information :

  1. The name of the method on which it make calls.
  2. Any argument (if any) of this method.
  3. The return value (if any) of this method.

Defining a Delegate in C#

when you want to create a delegate in C# you make use of delegate keyword.

The name of your delegate can be whatever you desire. However, you must define the delegate to match the signature of the method it will point to. fo example the following delegate can point to any method taking two integers and returning an integer.

public delegate int DelegateName(int x, int y);

A Delegate Usage Example

namespace MyFirstDelegate

{

    //This delegate can point to any method,

    //taking two integers and returning an

    //integer.

    public delegate int MyDelegate(int x, int y);

    //This class contains methods that MyDelegate will point to.

    public class MyClass

    {

        public static int Add(int x, int y)

        {

            return x + y;

        }

        public static int Multiply(int x, int y)

        {

            return x * y;

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            //Create an Instance of MyDelegate

            //that points to MyClass.Add().

            MyDelegate del1 = new MyDelegate(MyClass.Add);

            //Invoke Add() method using the delegate.

            int addResult = del1(5, 5);

            Console.WriteLine("5 + 5 = {0}\n", addResult);

            //Create an Instance of MyDelegate

            //that points to MyClass.Multiply().

            MyDelegate del2 = new MyDelegate(MyClass.Multiply);

            //Invoke Multiply() method using the delegate.

            int multiplyResult = del2(5, 5);

            Console.WriteLine("5 X 5 = {0}", multiplyResult);

            Console.ReadLine();

        }

    }
}

Delegate ability to Multicast

Delegate ability to multicast mean that a delegate object can maintain a list of methods to call, rather than a single method
if you want to add a method to the invocation list of a delegate object , you simply make use of the overloaded += operator, and if you want to remove a method from the invocation list you make use of the overloaded operator -= .

Note:Multicast delegate must contain only methods that return void, or you will get a run time exception.

A Multicast Delegate Example

namespace MyMulticastDelegate

{

    //this delegate will be used to call more than one

    //method at once

    public delegate void MulticastDelegate(int x, int y);

    //This class contains methods that MyDelegate will point to.

    public class MyClass

    {

        public static void Add(int x, int y)

        {

            Console.WriteLine("You are in Add() Method");

            Console.WriteLine("{0} + {1} = {2}\n", x, y, x + y);

        }

        public static void Multiply(int x, int y)

        {

            Console.WriteLine("You are in Multiply() Method");

            Console.WriteLine("{0} X {1} = {2}", x, y, x * y);

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            //Create an Instance of MulticastDelegate

            //that points to MyClass.Add().

            MulticastDelegate del = new MulticastDelegate(MyClass.Add);

            //using the same instance of MulticastDelegate

            //to call MyClass.Multibly() by adding it to it's

            //invocation list.

            del += new MulticastDelegate(MyClass.Multiply);

            //Invoke Add() and  Multiply() methods using the delegate.

            //Note that these methods must have a void return vlue

            Console.WriteLine("****calling Add() and Multibly() Methods.****\n\n");

            del(5, 5);

 

            //removing the Add() method from the invocation list

            del -= new MulticastDelegate(MyClass.Add);

            Console.WriteLine("\n\n****Add() Method removed.****\n\n");

            //this will invoke the Multibly() method only.

            del(5, 5);

        }

    }

}

Delegate Covariance

Assume you are designing a delegate that can point to methods returning a custom class type:

//Define a delegate pointing to methods returning Employee types.

public delegate Employee EmployeeDelegate();

if you were to derive a new class from Employee Type named SalesEmployee and wish to create a delegate type that can point to methods returning this class type you would be required to define an entirely new delegate to do so

//a new  delegate pointing to methods returning SalesEmployee types.

public delegate SalesEmployee SalesEmployeeDelegate();

Example

namespace MyEmployeesDelegate

{

    //Define a delegate pointing to methods returning Employee types.

    public delegate Employee EmployeeDelegate();

    //a new  delegate pointing to methods returning SalesEmployee types.

    public delegate SalesEmployee SalesEmployeeDelegate();

    class Program

    {

        public static Employee GetEmployee()

        {

            return new Employee();

        }

        public static SalesEmployee GetSalesEmployee()

        {

            return new SalesEmployee();

        }

        static void Main(string[] args)

        {

            EmployeeDelegate empDel = new EmployeeDelegate(GetEmployee);

            Employee emp = empDel();

            SalesEmployeeDelegate salesEmpDel = new SalesEmployeeDelegate(GetSalesEmployee);

            SalesEmployee emp2 = salesEmpDel();

        }

    }

    public class Employee

    {

        protected string firstName;

        protected string lastName;

        protected int Age;

        public Employee()

        { }

        public Employee(string fName, string lName, int age)

        {

            this.firstName = fName;

            this.lastName = lName;

            this.Age = age;

        }

 

    }

    public class SalesEmployee : Employee

    {

        protected int salesNumber;

        public SalesEmployee()

        { }

        public SalesEmployee(string fName, string lName, int age, int sNumber): base(fName, lName, age)

        {

            this.salesNumber = sNumber;

        }

    }

}

It would be ideal to build a single delegate type that can point to methods returning either Employee or SelesEmployee types.
Covariance allows you to build a single delegate that can point to methods returning class types related by classical inheritance.

Delegate Covariance Example

namespace DelegateCovariance

{

    //Define a single delegate that may return an Employee

    // or SalesEmployee

    public delegate Employee EmployeeDelegate();

    class Program

    {

        public static Employee GetEmployee()

        {

            return new Employee();

        }

        public static SalesEmployee GetSalesEmployee()

        {

            return new SalesEmployee();

        }

        static void Main(string[] args)

        {

            EmployeeDelegate emp = new EmployeeDelegate(GetEmployee);

            Employee emp1 = emp();

            EmployeeDelegate empB = new EmployeeDelegate(GetSalesEmployee);

            //to obtain a derived type you must perform an explicit cast.

            SalesEmployee emp2 = (SalesEmployee)empB();

        }

    }

    public class Employee

    {

        protected string firstName;

        protected string lastName;

        protected int Age;

        public Employee()

        { }

        public Employee(string fName, string lName, int age)

        {

            this.firstName = fName;

            this.lastName = lName;

            this.Age = age;

        }

    }

    public class SalesEmployee : Employee

    {

        protected int salesNumber;

        public SalesEmployee()

        { }

        public SalesEmployee(string fName, string lName, int age, int sNumber): base(fName, lName, age)

        {

            this.salesNumber = sNumber;

        }

    }

}

I hope you are now have a good idea with the creation and usage of delegates types.

Monday, March 10, 2008 10:28:46 AM (Jerusalem Standard Time, UTC+02:00)  #    Comments [0] - Trackback
.Net | AJAX | Microsoft | Programming | C#
# Thursday, February 28, 2008

Over my course of .NET development, I have compiled a list of essential free tools for .NET applications. This is not a the alpha or the omega of tools, just a short list that I feel is essential.

  1. SharpDevelop

    http://www.icsharpcode.net/OpenSource/SD/Download
    An open source IDE for .NET. Check out the full feature tour.


  2. Visual Web Developer Express Edition

    http://www.microsoft.com/express/vwd
    Stripped down version of Visual Studio that allows you to write .NET web applications.


  3. TortoiseSVN

    http://tortoisesvn.net/downloads
    There is no better Subversion client for Windows. You need this if you are going to use VisualSVN with Visual Studio.


  4. NAnt

    http://nant.sourceforge.net
    .NET based automation tool that has many built in tasks but could be extended with custom code written in any .NET language.


  5. Snippet Compiler

    http://www.sliver.com/dotnet/SnippetCompiler
    Snippet compiler is a small tool to write and execute small chunks of .NET code without creating a Visual Studio project.


  6. .NET Reflector

    http://www.aisto.com/roeder/dotnet
    Reflector is the class browser, explorer, analyzer and documentation viewer for .NET. Reflector allows to easily view, navigate, search, decompile and analyze .NET assemblies in C#, Visual Basic and IL.


  7. Microsoft SQL Server Management Studio Express

    http://www.microsoft.com/downloads/details.aspx?FamilyID=c243a5ae-4bd1-4e3d-94b8-5a0f62bf7796&displaylang=en
    Tool for database administration and development from Microsoft


  8. Quest Comparison Suite for SQL Server

    http://www.quest.com/Comparison-Suite-for-SQL-Server
    Compare and synchronize database schema and data


  9. XYPlorer

    http://www.xyplorer.com
    Awesome file manager. The older version is completely free.


  10. Convert C# to VB.NET

    http://labs.developerfusion.co.uk/convert/csharp-to-vb.aspx
  11. NAnt Add-In

    http://www.netlogics.ch/devcenter/display/NLC/NAntAddin
    Visual Studio add-in for NAnt integration


  12. NUnit Add-In

    http://www.netlogics.ch/devcenter/display/NLC/NUnitAddin
    Visual Studio add-in for NUnit integration
Thursday, February 28, 2008 2:53:42 PM (Jerusalem Standard Time, UTC+02:00)  #    Comments [0] - Trackback
.Net | Microsoft | Programming | Visual Studio
# Sunday, December 09, 2007

Last week (december 5th) Microsoft announced the Volta technology preview, a developer toolset for building multi-tier web applications using existing and familiar tools, techniques and patterns.

Volta’s declarative tier-splitting enables developers to postpone architectural decisions about distribution until the last possible responsible moment. Also, thanks to a shared programming model across multiple-tiers, Volta enables new end-to-end profiling and testing for higher levels of application performance, robustness, and reliability. In effect, Volta extends the .NET platform to further enable the development of software+services applications, using existing and familiar tools and techniques.

You architect and build your application as a .NET client application, assigning the portions of the application that run on the server tier and client tier late in the development process.

After tier assignments, Volta's deep integration with Visual Studio debugger and testing infrastructure dramatically improves the deployment experience for developers.

  • Volta automatically creates communication, serialization, and remoting code. Developers simply write custom attributes on classes or methods to tell Volta the tier on which to run them.
  • Developers may base tier assignments on any criteria, such as load management, performance, or location of critical assets and capabilities. Because Volta automates the hidden plumbing code, it is easy for developers to experiment with varying assignments of classes and methods to tiers.
  • Developers can use all the .NET languages, libraries, and tools they already know, including debuggers, profilers, test generators, refactoring, and code analysis tools.

Volta offers deep integration with Visual Studio 2008, including debuggers, profilers, and testing frameworks. Developers can step through code seamlessly from one tier to another, can set breakpoints on any tier, and trace flows of control across distributed systems.

What do you need to use Volta?

The Volta developer toolset requires Visual Studio 2008 and the .NET Framework 3.5 for writing and building applications. Volta applications run virtually anywhere, even where an MSIL runtime is not available. A Volta client-side application can run in most standards-compliant browsers, but can also be targetted also take advantage of MSIL runtimes like the .NET CLR.
 
All this sounds great, except the requirements that are trying to enforce the developers to use Visual Studio 2008 and the new .NET Framework 3.5.
 
I wonder why the long wait for this release? And why it does not compatible with .NET Framework 2.0?
 
BTW, It is just me or the Volta logo reminds firefox logo a bit:
 

  <- VS ->   

Sunday, December 09, 2007 2:41:46 PM (Jerusalem Standard Time, UTC+02:00)  #    Comments [0] - Trackback
.Net | Microsoft | Programming | Visual Studio | Volta
# Tuesday, December 04, 2007

Now that the .NET Framework 3.5 has been released, this version includes logic to detect the presence of the .NET Framework 3.5 and also .NET Framework 3.0 service packs, which was missing from previous versions of this sample code.

You can download updated versions of the sample code at the following locations:

For reference, the registry locations used in this sample code to detect the .NET Framework 3.0 service pack level and the .NET Framework 3.5 are listed below.

To detect the .NET Framework 3.0 service pack level:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.0]
SP = <value>

Note - this SP value will not exist at all if you only have the original release of the .NET Framework 3.0.  This value was added starting in the .NET Framework 3.0 SP1 and will be updated for future service packs.

To detect the .NET Framework 3.5 final release:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5]
Install = 1
Version = 3.5.21022.08

To detect the .NET Framework 3.5 service pack level:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5]
SP = <value>

Note - this SP value does exist in the final release of the .NET Framework 3.5, and will be set to 0.  Future service packs will increment this value as appropriate.

Tuesday, December 04, 2007 5:01:18 PM (Jerusalem Standard Time, UTC+02:00)  #    Comments [0] - Trackback
.Net | Microsoft | Visual Studio
Navigation
Archive
<July 2010>
SunMonTueWedThuFriSat
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Guy Levin
Sign In
Statistics
Total Posts: 63
This Year: 0
This Month: 0
This Week: 0
Comments: 14
Themes
All Content © 2010, Guy Levin