My understanding of delegates is that delegate is a special object that containts sequence of pointers to methods (each method should have the same return type and parameters).
Lets consider that we defined delegate like that
delegate int MyDelegate(string name, int age);
We can use it later in code like that
// creating the instance of delegate
MyDelegate objDelegate = null;
// initialising that instance
objDelegate = (string name, int age) =>
{
Console.WriteLine("Anonymous method is starting to work");
return age 2;
};
// execution of some method whith delegate as last parameter
objProgram.PrintBaseInfo("example", -2, objDelegate);
But why I can pass methods WITHOUT creating a delegate for them?
objProgram.PrintBaseInfo("Alexandr", 23, anotherClass.MyMethod);
In the example above i'm just passing method of some class (not delegate). My assumption is that compiler creates delegate for it and initializes it with this method, but i'm not sure.
PS Just to remove misunderstanding of question, here is definiton of PrintBaseInfo:
public void PrintBaseInfo(string name, int age, MyDelegate InnerFunc){some code}
CodePudding user response:
You are right, compiler will create delegate for you.
using System;
public class SomeClass
{
public void TakesAction(Action action)
{
}
public void CallsTakesAction()
{
TakesAction(MethodName);
}
public static void MethodName()
{
}
}
Is compiled to:
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
public class SomeClass
{
public void TakesAction(Action action)
{
}
public void CallsTakesAction()
{
TakesAction(new Action(MethodName));
}
public static void MethodName()
{
}
}
