C# - Switch statement

I am always interested in writing one or two lines less and I saw a technique employed quite a lot when using Switch statements in C#. Directly below is the way I have always written the statements. Basically the execution line of the first two statements are identical, however, the case line is quite different.

XmlTextReader xr = new XmlTextReader(@"C:\test\test.xml");
while (!xr.EOF)
{
    switch (xr.NodeType)
    {
        case XmlNodeType.EndElement:
            Console.WriteLine(xr.Name.ToString());
            break;
        case XmlNodeType.Element:
            Console.WriteLine(xr.Name.ToString());
            break;
        case XmlNodeType.Text:
            Console.WriteLine(xr.Value.ToString());
            break;
    }
    xr.Read();
}

As a short cut you can completely eliminate the first line of execution and it associated "break;" statement as follows. Now both lines will execute the same line of code:

XmlTextReader xr = new XmlTextReader(@"C:\test\test.xml");
while (!xr.EOF)
{
    switch (xr.NodeType)
    {
        case XmlNodeType.EndElement:
        case XmlNodeType.Element:
            Console.WriteLine(xr.Name.ToString());
            break;
        case XmlNodeType.Text:
            Console.WriteLine(xr.Value.ToString());
            break;
    }
    xr.Read();
}

I did not like this shortcut for case statements at first, but I realized that it was due to a small portions of my mind that still thinks in VB6. I do not believe there is a "break;" necessary in VB6. In fact the Select Case statement in VB 6 executes only one of several statements based on the value of the expression.

Technorati tags: ,


Comment Section

Comments are closed.