AJ Blog A BloG for TechniCaL DiscussIoN

4Aug/100

Delegates in C#

I just want to give an example about delegates in C#. Here I discuss how to create a simple delegate.

Note that, I am using console application for this example.

Create a console application in C#, add a new class with the name Delegates.cs

First we have to define what type of delegate we are going to use

Eg: public delegate string DoProcess(string dat);

Also the method what we are going to use with delegate should have the same signature.
That means, both should have the same return type and input parameters.
Eg: private string PrintData(string name)

See the example below,

File : Delegates.cs

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

namespace AJBlogCSharp.Examples.Delegates
{
    public delegate string DoProcess(string dat); //delegate decleration
    class Delegates
    {
        // This is the method we are going to use with delegate
        private string PrintData(string name)
        {
            name = "Hello :" + name + " This is the output of Delegate Example \n";
            return name;
        }
        // Method to implement the use of delegate
        public void RunDelegate()
        {
            string strName = null;
            Console.WriteLine("Welcome To Delegate Example ");
            Console.WriteLine("Enter Your Name: ");
            strName = Console.ReadLine();
            // Create object for delegate
            DoProcess doP = new DoProcess(PrintData);
            strName = doP(strName); // passing user input to PrintData through delegate object
            Console.WriteLine(strName);
        }

    }
}

In the above example, the delegate is defined outside the class. So that other classes in the namespace can use the same delegate.

The line "DoProcess doP = new DoProcess(PrintData);" creates object of the delegate "DoProcess" with the reference method "PrintData" inside the "Delegates" class.The input received from user is passed through the delegate object "doP(strName)" to the "PrintData" method. "Console.WriteLine(strName);" line displays the return value of "PrintData" in the screen.

Download Source code

Popularity: 49% [?]

Technorati Tags: , ,

21Aug/090

How to check a file whether exists in the corresponding folder or not ? – C#

Use the following synatax to check a file whether it is exists in the corresponding folder or not. System.IO.File.Exists(Filepath+Filename)

Popularity: 2% [?]

Technorati Tags: , ,