Underlying references of named method C# with Example



Underlying references of named method C# with Example

 

delegates 
When assigning named methods to delegates, they will refer to the same underlying object if: 
They are the same instance method, on the same instance of a class 
They are the same static method on a class 
public class Greeter 
{ 
public void WriteInstance() 
{ 
Console.WriteLine("Instance"); 
} 
public static void WriteStatic() 
{ 
Console.WriteLine("Static"); 
} 
} 
// ... 
Greeter greeter1 = new Greeter(); 
Greeter greeter2 = new Greeter(); 
Action instance1 = greeter1.WriteInstance; 
Action instance2 = greeter2.WriteInstance; 
Action instance1Again = greeter1.WriteInstance; 
Console.WriteLine(instance1.Equals(instance2)); // False 
Console.WriteLine(instance1.Equals(instance1Again)); // True 
Action @static = Greeter.WriteStatic; 
Action staticAgain = Greeter.WriteStatic; 
Console.WriteLine(@static.Equals(staticAgain)); // True 

0 Comment's

Comment Form

Submit Comment