Guest User

Untitled

a guest
Jan 19th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. namespace AnonymousFunctionVsmethodGroup
  2. {
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. var app = new App();
  8. app.Run();
  9. app.Crash();
  10. }
  11. }
  12.  
  13. public class App
  14. {
  15. private Func<string> m_Func;
  16.  
  17. public void Run()
  18. {
  19. Entity cat = null;
  20.  
  21. // Anonymous function. At this point cat is null
  22. m_Func = () => cat?.GetName();
  23.  
  24. // Initializing new cat
  25. cat = new Entity("Cat");
  26.  
  27. // Func is executed on a valid cat
  28. Console.WriteLine(m_Func());
  29. Console.Read();
  30. }
  31.  
  32. public void Crash()
  33. {
  34. Entity cat = null;
  35.  
  36. // Method group. At this point cat is null. Code never gets through here and an exception is thrown instead.
  37. // "Delegate to an instance method cannot have null this"
  38. m_Func = cat.GetName;
  39.  
  40. // Initializing new cat
  41. cat = new Entity("Cat");
  42.  
  43. // Func is executed on a valid cat?
  44. Console.WriteLine(m_Func());
  45. Console.Read();
  46. }
  47. }
  48.  
  49. // Sample entity
  50. public class Entity
  51. {
  52. private string name;
  53.  
  54. public Entity(string name)
  55. {
  56. this.name = name;
  57. }
  58.  
  59. public string GetName()
  60. {
  61. return name;
  62. }
  63. }
  64. }
Add Comment
Please, Sign In to add comment