Posts Tagged Extension Methods

I’m back!

It’s been almost a year since I wrote on my blog post. That’s way too long! It’ll defiantly not take that long until next time, I promise!!

Here is a little tip on how you can extend .NET built-in objects. With something called Extension Methods you can add a method to e.g. the String object (just like you can in JavaScript). Below is a little extension method that I find useful. From time to time you want to repeat a string X amount of times. With this String.Repeat() extension you can do that like so:

Example

string reallyAngry = "Argh ".Repeat(3);
// reallyAngry is now: "Argh Argh Argh ".

StringExtensions.cs

using System;
using System.Text;

public static class StringExtensions
{
    public static string Repeat(this string self, int count)
    {
        if (count <= 0)
        {
            return String.Empty;
        }
        else
        {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < count; i++)
            {
                builder.Append(self);
            }
            return builder.ToString();
        }
    }
}
Repeat

, , , ,

No Comments