Delegate - Overview and Sample Codes in C#


Delegate - Overview and Sample Codes in C#


Delegates

- Delegate lets developer pass function reference to a method that inturn calls that function.
- In some cases, when we want to log some information asynchronously, we use delegates.
- Delegate defines the signature of function along with return type.

Steps to define and use delegates

- declaration – declares the delegate
- instantiation – creates object of delegate with functionname mapping
- invocation – invokes the delegate to pass the function to a method that inturn execute the passed function

Delegate samples


1. A very simple example of delegate (MySampleDelegate1.cs):
--------------------------------------------------------

Class that contains the delegate and testing code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestingDelegate
{

// Declaration
public delegate void MySampleDelegate();

public class SimpleteDelegateTest1
{
public static void MyFunc()
{
Console.WriteLine("This was invoked via delegate !!");
Console.ReadKey();
}

public static void Main()
{
// Instantiation
MySampleDelegate MySampleDelegate = new MySampleDelegate(MyFunc);

// Invocation
MySampleDelegate();
}
}
}




Compile and test it
Output::
This was invoked via delegate !!

2. Example in which static function is passed to delegate (MySampleDelegate2.cs):
----------------------------------------------------------------------------

Class that contains the delegate and other validation:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestingDelegate
{
public class SimpleteDelegate2
{
// declare delegate
public delegate void MySampleDelegate(string message);

// validate and call
public void InvokeDelegate(MySampleDelegate MySampleDelegate)
{
if (MySampleDelegate!= null)
{
MySampleDelegate("Call is successfull");
}
else
{
MySampleDelegate ("Call is unsuccessfull");
}
}
}
}


test Client:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestingDelegate
{
public class MySampleDelegateTest2
{
// Function that is to be called with delegate
static void FunctionName(string message)
{
Console.WriteLine("This was invoked via delegate !! " + message);
Console.ReadKey();
}
public static void Main(string[] args)
{
// create instance of MyClass
SimpleteDelegate2 myClass = new SimpleteDelegate2();

// create instance of delegate from MyClass
SimpleteDelegate2.MySampleDelegate MySampleDelegate = new
SimpleteDelegate2.MySampleDelegate(FunctionName);

// call a method of MyClassthat inturn will invoke delegate with message
myClass.InvokeDelegate(MySampleDelegate);
}
}
}




Compile program and test the output

This was invoked via delegate !! Call is successfull
This was invoked via delegate !! Call is unsuccessfull


3. Example in which we store some log-information in a log-file (MySampleDelegate3.cs):
-------------------------------------------------------------------------------------

In this class we will … pass log file name in constructor and prepape the file to store messages. And FunctionName() will write the message along with date time stamp in the log file.

Class for Passing parameter (Entity class):

Create a public class CustomClass3.cs with 2 public properties …

1. string Message
2. string UserName

Class to Log message along with user name :



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;

namespace TestingDelegate
{
class LoggerClass3
{
FileStream fileStream;
StreamWriter streamWriter;

// Constructor
// this will receive filename separatly from the test client
public LoggerClass3(string filename)
{
fileStream = new FileStream(filename, FileMode.Create);
streamWriter = new StreamWriter(fileStream);
}

// Member Function which is used in the Delegate
// this will be invoked through delegate only
// removed static because it streamWriter can not be accessed from static function
public void FunctionName(CustomClass3 customClass3)
{
Console.WriteLine("This was invoked via delegate on " + customClass3.Message);
streamWriter.WriteLine(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + " - " +
customClass3.Message);
}

// this will be called from test client direcly
public void Close()
{
streamWriter.Close();
fileStream.Close();
}
}
}




Class that contains the delegate and other validation:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestingDelegate
{
public class SimpleteDelegate3
{
// declare delegate that received a custom object
public delegate void MySampleDelegate(CustomClass3 customClass3);

// validate and call
public void InvokeDelegate(MySampleDelegate MySampleDelegate, CustomClass3 customClass3)
{
if (MySampleDelegate != null)
{
MySampleDelegate(customClass3);
}
else
{
MySampleDelegate(customClass3);
}
}
}
}




Test Client (It can be a console application) :



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestingDelegate
{
public class MySampleDelegateTest3
{
public static void Main(string[] args)
{
// create Message Class
CustomClass3 customClass3 = new CustomClass3();

// passing myFile.log to logger file constructor
LoggerClass3 loggerClass3 = new LoggerClass3(@"d:\myFile.log");

// create instance of MyClass
SimpleteDelegate3 myClass = new SimpleteDelegate3();

// create instance of delegate from MyClass
SimpleteDelegate3.MySampleDelegate MySampleDelegate = new
SimpleteDelegate3.MySampleDelegate(loggerClass3.FunctionName);

// call a method of MyClass that in-turn will invoke delegate with message
// -- Log first message
Console.WriteLine("Call 1 - Start");
customClass3.Message = "Message 1";
customClass3.UserName = "username 1";
myClass.InvokeDelegate(MySampleDelegate, customClass3);
Console.WriteLine("Call 1 - End");

Console.WriteLine("Call 2 - Start");
// call a method of MyClass that in-turn will invoke delegate with message
// -- Log second message
customClass3.Message = "Message 2";
customClass3.UserName = "username 2";
myClass.InvokeDelegate(MySampleDelegate, customClass3);
Console.WriteLine("Call 2 - End");

// close logger class's filestream
loggerClass3.Close();
Console.ReadKey();
}
}
}




Compile program and test the output



I hope, this article is able to give you an insight to the Delegates.

Regards.


Comments

Author: nomzz33317 Apr 2010 Member Level: Bronze   Points : 2

It seems to me different type of post,actually i was surfing net to get data related to my projects mentioned under and in the meantime came here...And find this post different one!Well someone who dont know about it may get interesting type of information from this post...

__________________________________
642-181 | 642-383 | 642-515 | 642-611

Author: Sharad Sharma19 Apr 2010 Member Level: Gold   Points : 1

Hi nomzz333

I am not sure, but may be you visited to this post by reading words like "Delegate" or "Sample Code in C#".

In case you need any kind of friendly help regarding C# coding or any thing else related to .Net please feel free to discuss.

Regards!

Author: john marsh29 Jun 2010 Member Level: Bronze   Points : 2

We continue to tell you about the developments that received diplomas at the 70-640 International Fishery Exhibition " RYBPROM -EXPO 2005 " held in November in Moscow. ASTU conjunction with the Southern Research Centre of RAS won mcts dumps the competition program, undertaken as part of the exhibition project , in the category " Innovation in the fishing industry. " Development Department staff "Aquaculture and aquatic resources , and laboratory Untz Sciences Aquaculture and biological resources "- "Creating a modern polnosistemnogo sturgeon fish farming , ccda training with a capacity of 100 tons of marketable fish "- was awarded the Medal of the Ministry of Agriculture . For details, we asked the heads of department " Aquaculture and aquatic 70-642 resources , Dr. biol . Sciences , prof. SV Ponomarev .

Author: stevemartyn01 Oct 2010 Member Level: Bronze   Points : 1

It seems to me different type of post,actually i was surfing net to get data related to my projects mentioned under and in the meantime came here...And find this post different one!Well someone who dont know about it may get interesting type of information from this post...70-503
70-504
70-505
70-510



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: