Delegate and Method


I have a delegate and a method. what are the steps to call that method (give technical steps)

  1. Create a delegate
  2. Create a function matching the signature as per the delegate or vice-versa
  3. Assign method to the delegate instance
  4. Call delegate function

The entire code looks like,




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Program
    {
        public delegate int MYDelegate(int x, int y);

        static void Main(string[] args)
        {
            MYDelegate d = AddNumbers;
            Console.WriteLine(d(20, 30).ToString());
            Console.ReadLine();
        }

        public static int AddNumbers(int a, int b)
        {
            return (a + b);
        }
    }

Implementing Singleton Design Pattern using C#

Hello friends,

All of you must be aware of what Singleton Design Pattern is. Just to define it in one line, It is a pattern which allows creation of one and only instance of a class. 

The practical scenario where you can go with this pattern is having a print job class instance, single running instance of an application etc. 

The best example is Google Talk desktop application.
Let us try to implement this pattern via C# code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPatternsDemo
{
    public class SingletonClass
    {
        private SingletonClass()
        {
        }

        //Implementation #1
        //static SingletonClass _instance = null;
        //public static SingletonClass GetInstance()
        //{
        //    if (_instance == null)
        //    {
        //        _instance = new SingletonClass();
        //    }
        //    return _instance;
        //}

        //Implementation #2
        //Be aware that in a multithreaded program, different threads could try
        //to instantiate a class simultaneously. For this reason, a Singleton
        //implementation that relies on an if statement to check whether the
        //instance is null will not be thread-safe. Do not use code like that!

        static readonly SingletonClass _instance = new SingletonClass();

        public static SingletonClass GetInstance
        {
            get
            {
                return _instance;
            }
        }

        public string GetWelcomeMessage()
        {
            return "Welcome to the Singleton world!! ";
        }
    }
}

The Singleton class above will be instantiated only once.
When the GetInstance is called, it will return the statically created instance of the class.