Posted By

Soft on 02/04/08


Tagged

c methods Net extension


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

umang_nine


Playing With Extension Methods


 / Published in: C#
 

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

  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
Posted By: ixia on February 7, 2008

You know in C# 3.0 you can use lambda expressions instead of delegates. The syntax is more terse and simpler.

You need to login to post a comment.