Read all lines of the file with Java, Ruby and C#

UPDATE: As of Dec 2009 C# provides analog of the ForEach method out of the box, you can read more here.

Yehuda Katz, in his post ”My 10 Favorite Things About the Ruby Language”, provides example of the reading all lines of the file, with Java and Ruby.

Java is a bit wordy:

static void run(String in) 
	throws FileNotFoundException {
		File input = new File(in);
		String line; Scanner reader = null;
		try {
			reader = new Scanner(input);
			while(reader.hasNextLine()) {
				System.out.println(reader.nextLine());
			}
		} finally { reader.close(); }
}

Ruby is much better:

def run(input)
	File.open(input, "r") do |f|
		f.each_line {|line| puts line }
	end
end

But what about C#? Look.

static void Run(string inp){
	Array.ForEach(File.ReadAllLines(inp), Console.WriteLine);
}

The only thing I do not like with this code is a fact that I cannot read it as a plain English sentence. This is because, for some reasons, Array.ForEach was not defined as extension method. Fix is quite easy. Lets add small extension to IEnumerable<T>:

using System;
using System.Diagnostics.Contracts;
using System.Collections.Generic;

public static class EnumerableExtensions
{
	public static void ForEach<T>(this IEnumerable<T> input, 
						Action<T> action)
	{
		Contract.Requires(input != null);
		Contract.Requires(action != null);

		foreach (var item in input)
		{
			action(item);
		}
	}
}

And then rewrite results:

static void Run(string inp){
	File.ReadLines(inp).ForEach(Console.WriteLine);
}

BTW, in contrast to first C# example, second one will read lines one by one.

UPDATE: As of Dec 2009 C# provides analog of the ForEach method out of the box, you can read more here. So code could be rewritten in this way:

static void Run(string inp){
	File.ReadLines(inp).Run(Console.WriteLine);
}

Have a nice day!

P.S. I am not quite sure, that provided is the best solutions in Java and Ruby. The purpose of this post is to illustrate C# abilities, not to find disabilities of others.