Nice String Extensions

Ya Wheel

I discovered 5 minutes ago, that all wheels, I gona tell you today, already succesfully invented. But my is the prettiest ))

"Repeat me 3 times".Repeat(3); // :P

I need this code for creating dynamic tree from dashes like this “-”.Repeat(level). Unfortunatelly I did’not saw this forum post :( with StringBuilder effecient version, and also special way for chars. Thats what I was really looking. My code unfortunatelly much less effecient, but what I invented is this cool design with extension method. Soo human.

string displayName = null;
string email = "web@mail"
displayName.Coalesce(Email); // what the result?

What this thing do! We all know about coalesce method in C# - “??”. But it checks for nulls and we need something like this big and also very human-named method IsNullOrEmpty! Yes, its one more wheel - herу is one of implementations, a coalesce methods for C# 2.0 or even 1.0. My use all new features of C# 3.0

Wheel Code

Here we go:

public static class StringExtension
{
    public static string Repeat(this string template, int repeatTime)
    {
        if (template == null) return null;
 
        int length = template.Length * repeatTime;
        char[] all_array = new char[length];
        for (int i = 0; i < length; i++)
        {
            all_array[i] = template[i % template.Length]; //i - (i / tl) * tl
        }
 
        return new string(all_array);
    }
 
    public static string Coalesce(this string template, params object[] list)
    {
        if (!string.IsNullOrEmpty(template)){ return template; }
 
        return ((string)(list.FirstOrDefault(
            item =&gt; item != null || (item is string && ((string)item) != string.Empty)
        ) ?? string.Empty));
    }
}

Add tests, if you like such stuff:

[TestClass()]
public class StringTest
{
 [TestMethod()]
 public void CoalesceTest()
 {
     string first = "First";
     string second = "Second";
     string nullValue = null;
 
     Assert.AreEqual(first, first.Coalesce(second));
     Assert.AreEqual(second, nullValue.Coalesce(second));
     Assert.AreEqual(second, "".Coalesce(second));
     Assert.AreEqual(string.Empty, nullValue.Coalesce(nullValue));
     Assert.AreEqual(string.Empty, nullValue.Coalesce());
 }
 
 [TestMethod()]
 public void RepeatTest()
 {
     string nullValue = null;
 
     Assert.AreEqual("", "".Repeat(3));
     Assert.AreEqual(null, nullValue.Repeat(3));
     Assert.AreEqual("---", "-".Repeat(3));
 }
}

kick it on DotNetKicks.com

Tags:

Leave a Reply