Method I Wish Was There: AsUri

I never got used to the .NET Uri type. It seems like I only had to use it occasionally and even then where I really only wanted to type a string url.

public static Uri AsUri(this string uri) { return new Uri(uri); }

This way I can just add a AsUri() when I forgot that I was supposed to pass a Uri instead of a string.

webclient.DownloadFileAsync( “http://blah.com”, filename );

doesn’t compile and so I can scratch my head once again and replace it.

webclient.DownloadFileAsync( “http://blah.com”.AsUri(), filename );

I like trivial things 🙂

Method I Wish Was There: IsWithin

I don’t think I like the name, but I couldn’t come up with something better.

public static bool IsWithin(this DateTime datetime, TimeSpan distance) {
  var now = DateTime.Now;
  return (now – datetime).Duration() < distance;
}
public static bool IsWithin(this DateTime datetime, TimeSpan distance, DateTime now) {
  return (now – datetime).Duration() < distance;
}

Coupled with extension methods from yesterday you can write code like this:

if ( postDate.IsWithin(24.Hours()) ) { … }

nice and readable.

Method I Wish Was There: Minutes, Hours, Seconds

Ok, the ruby lovers will laugh, the ruby haters will, well, hate.

public static TimeSpan Minutes (this int minutes) {
  return new TimeSpan(0, minutes, 0);
}
public static TimeSpan Hours (this int hours) {
  return new TimeSpan(hours, 0, 0);
}
public static TimeSpan Seconds (this int seconds) {
  return new TimeSpan(0,0, seconds);
}

So that now I can write readable code like this:

var fiver = 5.Seconds();
var fivertoo = 5.Hours();
Assert.That( fiver.IsLessThan(fivertoo) );

Method I Wish Was There: DataGridView.GetDisplayIndexToPropertyNameMap

Alright, I’ll admit it, this one is rather obscure and only useful if you are doing strange things with a Windows Forms DataGridView.

I like this method because I think its a good use of Fold… err.. I mean Aggregate. I’m convinced Aggregate is an underutilized method so far by .NET developers.

In this case I like it because I can state what I want to do in a single statement rather than multiple statements.

public static IDictionary<int, string> GetDisplayIndexToPropertyNameMap(this DataGridView datagridview)
{
  var boundColumns = 
          datagridview.Columns.Cast<DataGridViewColumn>().Where(c => null != c.DataPropertyName);
  return boundColumns.Aggregate(
                new Dictionary<int, string>(),
                (a, b) => a.Insert(b.DisplayIndex, b.DataPropertyName));
   }

Notice the use of yesterday’s Dictionary.Insert so that we return the Dictionary at every iteration of the Aggregate*.

I find this MUCH more readable than if the Aggregate statement had been

return boundColumns.Aggregate(new Dictionary<int,string>(),
   (a,b) => { a.Add(b.DisplayIndex, b.DataPropertyName); return a; } );

The curly braces for the block lambda syntax and the return statement inside them really take away from the readability IMO.

* Note that this is why I put Insert explicitly on Dictionary instead of IDictionary. C# 3’s type inference is not good enough to figure out that we would want the signature of Aggregate to be IDictionary<int,string> instead of Dictionary<int,string> if Insert returned an IDictionary

Method I Wish Was There: Dictionary.Insert

Yes, this is a horrible name. If you have a better suggestion, I’m very welcome to it.

Here is the point: I want a method on Dictionary that does what Add does, but returns the dictionary instead of void. That way I can do this.

var d = (new Dictionary<string,string>()).Insert(“hi”,”mom”).Insert(“hello”,”dad”).Insert(“peace”,”sista”).Insert(“word”,”brotha”)

And yes, I know that C# 3’s initializer syntax lets me do this instead:

new Dictionary { { “hi”,”mom” }, {“hello”,”dad”}, {“peace”,”sista”}…}

BUT… that only works with a constructor. Tomorrow’s edition will show why I want a method instead of an initializer.

* I didn’t know that initializer is not a dictionary word. I love when fields (programming) extend their own words.

Method I Wish Was There: IEnumerable.IsNullOrEmpty

This one is a bit controversial because what I’m really saying is that I want to call an extension method on null and have it return true, rather than a Null Reference Exception. This violates the best practice of keeping null semantics on extension methods, but it makes my code so easy to write, so I don’t care, I wish it was there.

public static bool IsNullOrEmpty<T>(this IEnumerable<T> source)
{
  if(source ==null) return true;
  var collection = source as ICollection<T>;
  if (null != collection && collection.Count==0) return true;
  var enumerator = source.GetEnumerator();
  return enumerator.MoveNext();
}

I say that it makes my code writable because I can write what I’m thinking.

if (somedata.IsNullOrEmpty()) takeAction(); else takeOtherAction();

Method I Wish Was There: string.Join

Yes, I know it is there as a static, but I want it as a method on IEnumerable<string>.

public static string Join(this IEnumerable<string> source, string joiner)
{
            if (source.Count() == 0)
                return "";
            return source.Aggregate((a,b) => a+ joiner + b);
}

So that when I’ve got some strings I can join them 🙂

var logmessage = people.Select(p=>p.Firstname).Join(“, “);

Method I Wish Was There: PipeTo

Too much F# rots the brain…

Ok, maybe not, but too much F# really changes your C#. I find myself wanting to |> something that isn’t really linq-able (not IEnumerable).

After talking it over with my LINQ guru – Chris Marinos – for a good name for this operation, we both agreed that PipeTo is a good name.

public static void PipeTo<T>(this T source, Action<T> action)
{
  action(source);
}

Sure, its a dead simple implementation, but it means that I can do this:

blah.Where(…).Aggregate(…).PipeTo(Console.WriteLine)

Method I Wish Was There: RegexIsMatch

I don’t like the verbosity of a couple days ago use of Regex(). That is not to say that I don’t still find the Regex extension method useful, but if I’m just matching I should say so.

var re = @“\d+-\d+-\d+-\d+”.Regex();
var match = re.Match(“things 10-12-5-1”);
//do things with match
var othermatch = re.Match(“stuff 1-6-8-9”);

Regex extension method is great. But for a Boolean statement I should be able to just say “RegexIsMatch?”

if ( someText.RegexIsMatch(@”\d+\.\d+”) ) …

Method I Wish Was There: ContainsDigit

Sometimes when dealing with lots of strings or parsing text, I don’t always want to turn directly to regular expressions. I might want to just say “if this thing has a digit”.

public static bool ContainsDigit(this string source) {
  return @"\d".Regex().IsMatch(source);
}

This uses yesterday’s Regex() extension method on string and simply returns true or false, exactly as it reads.

string field1 = GetFieldFromSomeParserOrSomething();
if (field1.ContainsDigit()) …