Playing With Extension Methods


/ Published in: C#
Save to your folder(s)

In Ruby you can write 5.times { print "Hello World" } . With a simple extension method I was able to do something similar with C#.


Copy this code and paste it in your HTML
  1. using System;
  2.  
  3. namespace ExtensionMethodTest
  4. {
  5. static class Program
  6. {
  7.  
  8. public delegate void MyDelegate();
  9.  
  10. static void Main(string[] args)
  11. {
  12.  
  13. 5.Times(delegate()
  14. {
  15. Console.WriteLine("Hello World");
  16. });
  17.  
  18. Console.Read();
  19. }
  20.  
  21. public static void Times(this int count, MyDelegate del)
  22. {
  23. for (int i = 0; i < count; i++)
  24. {
  25. del();
  26. }
  27. }
  28.  
  29. }
  30. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.