Next post: 0xBAADF00D

C#3 Extension Methods

I like some of the new C# 3.0 features. Extension methods are fun to play around with. Isn't this ridiculous:
(4).Square().ToString().PrintToConsole();
No performance drawbacks, and so much fun!

On a more useful note, I've written some extension methods that have been serving me well. (We've just upgraded to Orcas at work.)
  internal static class StringExtensions
  {
    public static void Print(this string str)
    {
      Console.WriteLine(str);
    }
    public static void Trace(this string str)
    {
      System.Diagnostics.Trace.WriteLine(str);
    }
    public static string Multiply(this string str, int n)
    {
      StringBuilder sb = new StringBuilder();
      for (int i = 0; i < n; i++)
        sb.Append(str);
      return sb.ToString();
    }
    public static string[] SimpleSplit(this string str, string strDelim)
    {
      return str.Split(new string[] { strDelim }, StringSplitOptions.None);
    }
    public static string SimpleJoin(this string[] astr, string strDelim)
    {
      return String.Join(strDelim, astr);
    }
    public static Boolean IsNullOrEmpty(this string str)
    {
      return String.IsNullOrEmpty(str);
    }
    public static int ToInt(this string str)
    {
      return int.Parse(str);
    }
    public static Boolean Contains<T>(this T[] a, T val)
    {
      return a.IndexOf<T>(val) != -1;
    }
    public static int IndexOf<T>(this T[] a, T val)
    {
      for (int i = 0; i < a.Length; i++)
        if (a[i].Equals(val))
          return i;
      return -1;
    }
    // Just like Python!
    public static TValue Get<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey keyTry, TValue defaultVal)
    {
      TValue ret;
      return dict.TryGetValue(keyTry, out ret) ? ret : defaultVal;
    }
  }
I wish you could overload operators - I wanted to see "ab" * 3 ("ababab") and do something insane like "text"++ becoming "TEXT".

C#3 also has introduced object initializers, which are nice. Still no dictionary initializers, though - I'm disappointed. Here's a workaround - I wish I could have used generics.
Dictionary<int, string> d = new Dictionary<int, string>();
d.AddMany( new object[] {4, "a", 5, "e", 6, "f"} );

public static void AddMany<TKey, TValue>(this Dictionary<TKey, TValue> dict,
  object[] aIn)
{
  if (aIn.Length % 2 != 0) throw new ArgumentOutOfRangeException();
  for (int i=0; i<aIn.Length; i+=2)
    dict[(TKey) aIn[i]] = (TValue) aIn[i + 1];
}