C# Programming - Delegates - Discussion

Discussion Forum : Delegates - General Questions (Q.No. 3)
3.
Which of the following is the necessary condition for implementing delegates?
Class declaration
Inheritance
Run-time Polymorphism
Exceptions
Compile-time Polymorphism
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
9 comments Page 1 of 1.

Sallu said:   9 years ago
If I define a struct and in that I define a method.

Then I bind that method with a delegate which is defined in the namespace.

Means there is no class in this whole scenario. So what's about class.

According to me, it's not mandatory to define a class for delegate.
(1)

Ambadas Mehtre said:   10 years ago
For using a delegate we create a class which contains methods to bind the delegate.

Yogesh said:   1 decade ago
Example:

using System;

public delegate string FirstDelegate (int x);

class DelegateTest
{
string name;

static void Main()
{
FirstDelegate d1 = new FirstDelegate(DelegateTest.StaticMethod);

DelegateTest instance = new DelegateTest();
instance.name = "My instance";
FirstDelegate d2 = new FirstDelegate(instance.InstanceMethod);

Console.WriteLine (d1(10)); // Writes out "Static method: 10"
Console.WriteLine (d2(5)); // Writes out "My instance: 5"
}

static string StaticMethod (int i)
{
return string.Format ("Static method: {0}", i);
}

string InstanceMethod (int i)
{
return string.Format ("{0}: {1}", name, i);
}
}

Nicholas Mahbouby said:   1 decade ago
The C# compiler generates a class from your delegate declaration. However in your C# code it is not required to use the class keyword to implement delegates.

delegate void MyDel(); // Declared outside of class.

struct MyStruct
{
public void Foo() { }
}

struct Test
{
void Test()
{
MyStruct myStruct = new MyStruct();
MyDel mydel = myStruct.Foo;
mydel();
}
}

Prajakta said:   1 decade ago
As per the options given "Class" is the only needful for delegates to happen.

Mike said:   1 decade ago
I read somewhere that delegates are implemented under the hold as am object (ie class) that wraps a 'method'. This is a very lose explaination, but I think this is what the answer is all about.

Mandava.bm said:   1 decade ago
There can be a delegate without class, because no matter what and where the class is, a delegate just need methods that has same method signature like it has...for eg 100 methods from 100 classes can be referred by a single delegate when the method signature is same. A delegate can also be declared in namespace scope, out of a class. No delegate is class specific or class dependent.

Madan Kumar said:   1 decade ago
For using a delegate we need a class which contains functions to bind to delegates.

Lal Singh Dhakad said:   1 decade ago
Why it is necessary to decalre a class for implementation of delegates ?

Post your comments here:

Your comments will be displayed after verification.