I'm a great fan of extensions in C#. See also this previous snippet.
Extensions are really simple to use. Start with adding a static class containing static methods.
Note the special use of the keyword this
in the Times extension method.
The next code snip is how you could use this extension, eliminating the use of the for.
Replacing the for loop, using extensions
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExtensionSpace // use a special namespace for extensions
{
public static class IntExtensions //extensions for the integer type
{
/// <summary>
/// Repeat an action until EndCount
/// Counting starts at zero, EndCount not included
/// </summary>
/// <param name="EndCount"></param>
/// <param name="action takes one int and returns void"></param>
public static void Times(this int EndCount, Action<int> action)
{
for (int i = 0; i < EndCount; i++)
{
action(i);
}
}
//more extension methods . . .
}
}
-----------------------------------------------------------------------------------
sing System;
using System.Collections.Generic;
using ExtensionSpace; // notice!
namespace Extensiontest
{
class Program
{
static void Main(string[] args)
{
// Write the square of the numbers 0 to 9 to the console
10.Times(n => DoTheSquare(n));
Console.WriteLine("=====================");
// Equivalent for loop
for (int i = 0; i < 10; i++)
{
DoTheSquare(i);
}
Console.ReadKey();
}
static void DoTheSquare(int n)
{
Console.WriteLine("The square of {0} is {1}", n, n * n);
}
}
}
Mike Askew 131 Veteran Poster Featured Poster
ddanbe 2,724 Professional Procrastinator Featured Poster
Ketsuekiame 860 Master Poster Featured Poster
deceptikon 1,790 Code Sniper Team Colleague Featured Poster
ddanbe commented: Thanks for sharing. +15
Ketsuekiame 860 Master Poster Featured Poster
deceptikon 1,790 Code Sniper Team Colleague Featured Poster
kplcjl 17 Junior Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.