What is the main difference between pointer and delegate with examples?

What is the main difference between pointer and delegate with examples?

The difference between pointer and delegate:-
Delegate:-A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked. Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and secure. 
Example:-
   using System;
 
 delegate void MyDelegate(string s);
 
 class MyClass
 {
public static void Hello(string s)
  {
 Console.WriteLine("  Hello, {0}!", s);
  }
public static void Goodbye(string s)
  {
Console.WriteLine("  Goodbye, {0}!", s);
 }
public static void Main()
{
MyDelegate a, b, c, d;
a = new MyDelegate(Hello);
b = new MyDelegate(Goodbye);
 c = a + b;   // Compose two delegates to make another
d = c - a;   // Remove a from the composed delegate
Console.WriteLine("Invoking delegate a:");
a("A");
 Console.WriteLine("Invoking delegate b:");
 b("B");
Console.WriteLine("Invoking delegate c:");
c("C");
 Console.WriteLine("Invoking delegate d:");
 d("D");
  }
}
Output
Invoking delegate a:
  Hello, A!
Invoking delegate b:
  Goodbye, B!
Invoking delegate c:
  Hello, C!
  Goodbye, C!
Invoking delegate d:
  Goodbye, D!
Code Discussion
Pointer:-C# statements execute in either a safe or an unsafe context. Safe context is the default, but any code using pointers requires unsafe context.
unsafe:-   Specifies unsafe context. 
Once you have a pointer to a variable, you must ensure that the variable isn't moved in memory by the garbage collector.
pointer holds reference to a variable or pointer is a variable which holds the address of another variable.
Example:-
         using System;
class UnsafeTest 
{
   // unsafe method: takes pointer to int
   unsafe static void SquarePtrParam (int* p) 
   {
      *p *= *p;
   }

   public static void Main() 
   {
      int i = 5;
      // unsafe statement for address-of operator
      unsafe SquarePtrParam (&i);
      Console.WriteLine (i);
   }
}
Output
25


By:kamal
Date:2015-10-10 00:00:00

Post Your Answers


User Email:

User Name:
Answers:

Related C Links

C interview questions and answers for experienced and fresher