We Recommend

Accelerated C# 2008 Accelerated C# 2008
This book is both a rapid tutorial and a permanent reference. You’ll quickly master C# syntax while learning how the CLR simplifies many programming tasks. You’ll also learn best practices that ensure your code will be efficient, reusable, and robust. Why spend months or years discovering the best ways to design and code C# when this book will show you how to do things the right way, right from the start?


Posted By

Soft on 02/04/08


Tagged

c methods Net extension


Versions (?)


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.