Extension Methods
Posted On Sunday, November 14, 2010 at at 5:06 AM by LokeshI was working on a Ruby on Rails project. I was partly influenced by the syntactic sugars.
Here is the extension method in C# for Ruby times
1: using System;
2:
3: namespace ConsoleApplication1
4: {
5: class Program
6: {
7: static void Main(string[] args)
8: {
9: 5.Times(DoSomething);
10: }
11:
12: private static void DoSomething(int x)
13: {
14: // Do something with x
15: }
16: }
17:
18: internal static class Extensions
19: {
20: public static void Times(this int times, Action<int> action)
21: {
22: for (var i = 0; i < times; i++)
23: action(i);
24: }
25: }
26: }