Among other awesome features introduced in C# 3.0 are amazing extension methods. It looks like taking on board dynamic-language-oriented people. Now this Ruby-style can be done in C#:
1.To(7).DoSomething();
Woohoo! It is amazing ... the feature is quite powerful and if you think about that a little bit intimidating for a static-language mind. You will be definitely more comfortable with the idea of such a freedom.
How you can do it ? With a small piece of smart code
public static class Extension
{
public static IEnumerable<int> To(this int from, int to)
{
return from < to
? Enumerable.Range(from, to - from + 1)
: Enumerable.Range(to, from - to + 1).Reverse();
}
public static void DoSomething(this IEnumerable<int> values)
{
foreach (int i in values)
{
Console.WriteLine(string.Format("{0} Count : {1}","Do Something",i));
}
}
}
And you can write
class Program
{
static void Main(string[] args)
{
1.To(7).DoSomething();
Console.ReadKey();
}
}
Enjoy yourself
{
public static IEnumerable<int> To(this int from, int to)
{
return from < to
? Enumerable.Range(from, to - from + 1)
: Enumerable.Range(to, from - to + 1).Reverse();
}
public static void DoSomething(this IEnumerable<int> values)
{
foreach (int i in values)
{
Console.WriteLine(string.Format("{0} Count : {1}","Do Something",i));
}
}
}
And you can write
class Program
{
static void Main(string[] args)
{
1.To(7).DoSomething();
Console.ReadKey();
}
}
Enjoy yourself
No comments:
Post a Comment