Question Delegate Confusion

ishtarsg

New member
Joined
Aug 20, 2015
Messages
1
Programming Experience
Beginner
Hi
I am quite confuse with Delegate
I see some examples like
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);
}
}

However i failed to see any advantage in using delegate. Why wouldn't someone write codes like. Wouldn't it be too troublesome to 'new' some other objects just to preform the same job?
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 (StaticMethod (10)); // Writes out "Static method: 10"
Console.WriteLine (InstanceMethod (5)); // Writes out "My instance: 5"
}
 

JohnH

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
1,194
Location
Norway
Programming Experience
10+

JohnH

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
1,194
Location
Norway
Programming Experience
10+
You also have some confusion about instance and static, this is not valid code:
Console.WriteLine (InstanceMethod (5)); // Writes out "My instance: 5"
compiler error:
An object reference is required for the non-static field, method, or property 'DelegateTest.InstanceMethod(int)'
Static Classes and Static Class Members (C# Programming Guide)
10.2.5 Static and instance members (C#)
Generally speaking, it is useful to think of static members as belonging to classes and instance members as belonging to objects (instances of classes).
 
Top Bottom