Alex Hoffman

Perspective on management, development and technology

Syndication

News

    Subscribe

    IASA Member

Adventures in .NET 3.5 Part 1

A "Print" To the Console

Because I write a lot of small console applications, I find myself typing ...

        Console.WriteLine("some text"); 

in C# again and again.  I've always pined for the ability to simply be able to have an object "Print" itself to the console.

In other words, I'd really like to be able to type statements like those below ...

      87.Print();
      "alex".Print();
      DateTime.Now.Print();
      typeof(int).Print();

Well .NET 3.5 makes that easy with Extension Methods.  Check out this post to get started.  The code to implement such a "Print" method is simple ... 

      public static void Print(this object o) {
          Console.WriteLine(o);
      }


 

Concatenation

Another thing I need to do all the time is output the contents of a collection as a string on a single line with a definable separator.  Now that we have a "Print" method, I'd like to be able to type ...

      /* output to the console: Soccer,Rugby,Tennis,Cricket */
      var sports = new string[] { "Soccer", "Rugby", "Tennis", "Cricket" };
      sports.Concatenate(",").Print();

Here's code to implement "Concatenate()".

      public static string Concatenate<T>(this IEnumerable<T> items, string separator)
      {
          StringBuilder buffer = new StringBuilder();
      
          int totalItems = items.Count();
          int counter = 0;
      
          foreach (var item in items)
          {
              buffer.Append(item);
              counter++;
      
              if (counter < totalItems)
                  buffer.Append(separator);
          }
      
          return buffer.ToString();
      }

 

Coming Next

Implementing Ruby Blocks in C# (well almost).

Published Saturday, August 04, 2007 3:34 PM by Alex Hoffman

Filed under: , ,

Comments

# Adventures in .NET 3.5 Part 2 - Ruby Blocks@ Saturday, August 04, 2007 5:18 AM

In my previous post , I talked about .NET 3.5 Extension Methods and ended by mentioning Ruby Blocks

Alex Hoffman

# Adventures in .NET 3.5 Part 3 - Ruby Blocks@ Monday, August 06, 2007 3:18 AM

This is the 3rd part in a series. See Part1 and Part 2 . Inferring a Collection Type In C# 3.5, the compiler

Alex Hoffman

# Adventures in .NET 3.5 Part 4@ Monday, August 06, 2007 9:33 PM

This is the 4th part in a series. See Part1 , Part 2 and Part3 . Extension Methods continued So, where

Alex Hoffman

# .net 3.5 - my recent presentation resources@ Wednesday, March 26, 2008 7:55 PM

Yesterday I presented to one of my financial services customers in the city on an overview of what's

Team Individualism