Monday, April 14, 2008

using Statement

With a using statement, your objects will dispose of themselves once out of scope of the using statement block. For example, you ever open a file or open a connection to a database and then at the end close your connection? The using statement can do this for you.
Before:
SqlConnection conn = null;
SqlCommand cmd = null;

try
{
    conn = new SqlConnection(connString);
    cmd = new SqlCommand(commandString, conn);

    conn.Open();
    cmd.ExecuteNonQuery();
}
finally
{
    if (cmd != null)
        cmd.Dispose();
    if (conn != null)
        conn.Dispose();
}
After:
using (SqlConnection conn = new SqlConnection(connString))
{
    using (SqlCommand cmd = new SqlCommand(commandString, conn))
    {
        conn.Open();
        cmd.ExecuteNonQuery();
    }
}
Can I do this with any object?
In order to use using, the object has to implement IDisposable. Notice the SqlConnection class:

IDisposable only has one method, "Dispose()". The implemented Dispose method on the IDisposable interface will get called as soon as execution leaves the using code block.
This is pretty interesting. Can you think of any of your classes where you have to perform some cleanup when done? You could implement IDisposable and then use your classes in using statements.

More Info: MSDN: using Statement

Sunday, April 13, 2008

Looping Through Your Class

You may want others who use your class to be able to loop through it. To make this possible your class has to use the interface IEnumerable and implement IEnumerable.GetEnumerator() method.
public class Family : IEnumerable
{
    private List<string> familyMembers = new List<string>()
            {
                //Collection Initializer
                "Mother", "Father", "Patty", "Bob"
            };

    public IEnumerator GetEnumerator()
    {
        foreach (string member in familyMembers)
        {
            if (member == "Mother")
                yield return "Claudia";
            else if (member == "Father")
                yield return "Phillip";
            else
                yield return member;
        }
    }
}
In your GetEnumerator function you can customize the way data is returned when a consumer does a foreach on your class.
Family family = new Family();
foreach (string member in family)
{
    Console.WriteLine(member);
}
More Info: MSDN: Iterators

Saturday, April 12, 2008

Using System.Diagnostics.StopWatch

In the old days if wanted to do a quick performance test you could write a test and track the start and end time and see what the difference was between them. Now there is a StopWatch class that can do this for you!
My friend Jake and I were talking about doing quick performance tests on exception handling. We can definitely use this handy class to help out with that.
using System.Diagnostics;

[Test]
public void StringBuilderTest()
{
    Stopwatch watch = new Stopwatch();
    watch.Start();

    StringBuilder sb = new StringBuilder();
    int iterations = 10000000; // 10 million
    for (int i = 0; i < iterations; i++)
    {
        sb.Append(i);
    }

    watch.Stop();
    Console.Write("Elapsed Time: " + watch.Elapsed);
}
More Info: MSDN: Stopwatch Class

Friday, April 11, 2008

Yield Keyword

You use yield to return values many times from one method call. The test below shows how this can be done: (Notice the first line uses a Collection Initializer)
private List<string> Names = new List<string>() { "Mark", "Matt" };

[Test]
public void RunLoopWithYield()
{
    string output = string.Empty;

    foreach (string yieldedValue in ReturnOneNameAtATime())
    {
        output += yieldedValue;
    }

    Assert.AreEqual("Start_Mark_Matt_End", output);
}

private IEnumerable<string> ReturnOneNameAtATime()
{
    // Return this first and then come back.
    yield return "Start_";

    foreach (string name in Names)
    {
        // Return one name at a time.
        yield return name + "_";
    }

    // Return this last but come back one last time
    // to actually exit method.
    yield return "End";
}
See how the path of execution is different with the yield statements:

Thursday, April 10, 2008

String vs. StringBuilder

String type is immutable. Immutable basically means "cannot be changed". Consider the following code:
   1:  string name = "Mark";
   2:  name += " Moeykens";
   3:  name = string.Format("Mr. {0}", name);
On line 1 a string was assigned "Mark". On line 2 "Mark" was thrown away and a new string was created, "Mark Moeykens". On line 3 "Mark Moeykens" was thrown away and a new string, "Mr. Mark Moeykens" was created. Since strings are immutable, a new place in memory has to be created everytime the value changes. StringBuilder manipulates strings much more efficiently. In cases where you have a lot of string manipulation, StringBuilder would be a better candidate.
StringBuilder sb = new StringBuilder();
sb.Append("Mark");
sb.Append(" Moeykens");
sb.Insert(0, "Mr. ");
Notes
  • StringBuilder still outperforms string when concatenating just two strings.
  • There is not much of a difference in time (milliseconds) until you go over about 10,000 concatenations
  • StringBuilder is a good choice for applications that need to scale, like web applications.

More Info: MSDN: Using the StringBuilder Class

Wednesday, April 9, 2008

TableAdapters

TableAdapters allow you to get data from a DataSet. You use DataSets to connect to a database and retrieve table schema information. Then when you want to get the data you use the table's TableAdapter.
TableAdapters are nothing more than classes with methods that you can create visually through a designer. The methods are sql queries.
So if you want to get a populated table you call one of these two premade methods.
MessageTableAdapter adapter = new MessageTableAdapter(); 
Message messageDataTable = adapter.GetData(); 
TableAdapters will:
  • Open a connection.
  • Query for the data.
  • Return the data in the table schema it is attached to.
  • Close the connection.

You can create as many methods as you want on the TableAdapter to:

  • Insert
  • Update
  • Delete
  • Select

More Info: MSDN: TableAdapter Overview

Tuesday, April 8, 2008

Extension Methods

You can write new methods to add to existing .NET classes without having to inherit the class. These can be common functions you always find yourself doing that you wish .NET could do out of the box. For example, doing string.Format on strings.
Before:
string name = "Mark"; 
string message = "Hello, my name is {0}."; 
return string.Format(message, name); 

After:
// ExtensionMethods.cs
public static class StringExtensionMethods
{
    public static string FormatThis(this string s, string arg)
    {
        return string.Format(s, arg);
    }
}

// Code elsewhere
string name = "Mark";
string message = "Hello, my name is {0}.";
return message.FormatThis(name);
Notice:
1. Your extension method and the class it is in has to be static.
2. The first argument is "this", "this" is the actual object you are extending.

More Info: Scott Guthrie: New "Orcas" Language Feature: Extension Methods