Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace AnonymousFunctionVsmethodGroup
- {
- class Program
- {
- static void Main(string[] args)
- {
- var app = new App();
- app.Run();
- app.Crash();
- }
- }
- public class App
- {
- private Func<string> m_Func;
- public void Run()
- {
- Entity cat = null;
- // Anonymous function. At this point cat is null
- m_Func = () => cat?.GetName();
- // Initializing new cat
- cat = new Entity("Cat");
- // Func is executed on a valid cat
- Console.WriteLine(m_Func());
- Console.Read();
- }
- public void Crash()
- {
- Entity cat = null;
- // Method group. At this point cat is null. Code never gets through here and an exception is thrown instead.
- // "Delegate to an instance method cannot have null this"
- m_Func = cat.GetName;
- // Initializing new cat
- cat = new Entity("Cat");
- // Func is executed on a valid cat?
- Console.WriteLine(m_Func());
- Console.Read();
- }
- }
- // Sample entity
- public class Entity
- {
- private string name;
- public Entity(string name)
- {
- this.name = name;
- }
- public string GetName()
- {
- return name;
- }
- }
- }
Add Comment
Please, Sign In to add comment