How To: Get Correct List of Files in Directory

Unfortunately well known method Directory.GetFiles() doesn’t always work as we (developers) would expect. Searching with pattern like “*.txt” in addition to expected txt files will return all the others having extension starting with txt (i.e. txt1).

This issue can be easily solved using LINQ like this:

Directory.GetFiles(".", "*.txt").Where(item => item.EndsWith(".txt"))

Here is simple program showing both file searching approaches in action:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Files found by Directory.GetFiles() contain INCORRECT list:");
        foreach (var file in Directory.GetFiles(".", "*.txt"))
	{
            Console.WriteLine(file);
	}
        Console.WriteLine();

        Console.WriteLine("Files found by query contain CORRECT list:");
        foreach (var file in Directory.GetFiles(".", "*.txt").Where(item => item.EndsWith(".txt")))
        {
            Console.WriteLine(file);
        }
        Console.WriteLine();

        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    }
}

Having three files “TextFile1.txt”, “TextFile2.txtext” and “TextFile3.txt1″ output is:
Files found by Directory.GetFiles() contain INCORRECT list:
.\TextFile1.txt
.\TextFile2.txtext
.\TextFile3.txt1

Files found by query contain CORRECT list:
.\TextFile1.txt

Press any key to exit...

Project is available for download here.

Implicit and Explicit Implementation of Interface

Difference Between Explicit and Implicit Implementation

Usually we implement interfaces implicitly. This has an advantage when we need to call method defined in interface: it can be called from variable either of type interface or class. In the same time explicitly implemented method cannot be called from variable of type class.

This is demonstrated by the code below:

namespace ExplicitInterfaceImplementation
{
    class Program
    {
        static void Main(string[] args)
        {
            Sample sampleObject = new Sample();

            CallExplicitlyImplementedMethod(sampleObject);
            CallImlicitlyImplementedMethod(sampleObject);

            Console.ReadLine();
        }

        static void CallExplicitlyImplementedMethod(Sample sampleObject)
        {
            // When uncommented next line will not compile.
            //sampleObject.ExplicitMethod();

            // This is how we can call explicitely implemented method.
            ISample sampleInterface = sampleObject as ISample;
            sampleInterface.ExplicitMethod();
        }

        static void CallImlicitlyImplementedMethod(Sample sampleObject)
        {
            // Next line will compile and execute without problems.
            sampleObject.ImplicitMethod();

            // Also we can call implicitely implemented method using interface.
            ISample sampleInterface = sampleObject as ISample;
            sampleInterface.ImplicitMethod();
        }
    }

    interface ISample
    {
        void ExplicitMethod();
        void ImplicitMethod();
    }

    class Sample : ISample
    {
        void ISample.ExplicitMethod()
        {
            Console.WriteLine("ExplicitMethod()");
        }

        public void ImplicitMethod()
        {
            Console.WriteLine("ImplicitMethod()");
        }
    }
}

One more important thing is that explicitly implemented method always public. For this reason C# doesn’t allow to use access modifier for the method.

Why Could We Need Explicit Implementation?

So explicit implementation narrows usage of the method. When can we have advantage of it in this case?

It is useful when implementing two interfaces containing methods with the same signature as shown in sample below:

namespace ExplicitInterfaceImplementationUsage
{
    class Program
    {
        static void Main(string[] args)
        {
            Operations operations = new Operations();

            IAddition addition = operations as IAddition;
            ISubtraction subtraction = operations as ISubtraction;

            Console.WriteLine(addition.Compute(1, 1));
            Console.WriteLine(subtraction.Compute(1, 1));

            Console.ReadLine();
        }
    }

    interface IAddition
    {
        int Compute(int left, int right);
    }
    interface ISubtraction
    {
        int Compute(int left, int right);
    }

    class Operations : IAddition, ISubtraction
    {
        int IAddition.Compute(int left, int right)
        {
            return left + right;
        }

        int ISubtraction.Compute(int left, int right)
        {
            return left - right;
        }
    }
}

Actually we could implement Compute() method implicitly from one interface and explicitly from another one. Nevertheless I wouldn’t recommend such solution because it will be even harder for client code to decide how to call Compute() method correctly.

I must confess I never had to use explicit interface implementation. So samples here are fake ones.

Did you have to use it in production code? Was it something else then you couldn’t change method name in interfaces because its in third-party library?

How To: Read String Line by Line

Breaking a string containing multi-line text to a list of lines can be easily done using StringReader. Here is a method that does this and small test program:


class Program
{
    static void Main(string[] args)
    {
        IList<string> lines = BreakLines("This is a test for breaking multiline string \nto a list of lines.");

        foreach (var item in lines)
        {
            Console.WriteLine(item);
        }

        Console.ReadLine();
    }

    private static IList<string> BreakLines(string text)
    {
        IList<string> lines = new List<string>();

        using (StringReader reader = new StringReader(text))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                lines.Add(line);
            }
        }

        return lines;
    }
}

 

“throw;” vs “throw ex;”

Sometimes exception gets caught to make some logging and rethrow it upper (i.e. log exception in library and then throw it to client code).

In this case it’s important to understand that “throw ex;” will cut stack trace. So when caught in calling code exception will contain StackTrace and TargetSite starting from the method that rethrown it. Sometimes it’s desirable to hide real stack trace, sometimes – not.

Lets take a look at following code:

class Program
{
       static void Main(string[] args)
       {
              Program p = new Program();
              p.ClientMethod();

              Console.ReadLine();
       }

       void ClientMethod()
       {
              try
              {
                     LibraryAPI();
              }
               catch (Exception ex)
              {
                      Console.WriteLine(ex.StackTrace);
              }
       }

       void LibraryAPI()
       {
              try
              {
                     LibraryInternal();
              }
               catch (Exception ex)
              {
                      throw ex;
              }
       }

       void LibraryInternal()
       {
               throw new Exception("Trace me if you can");
       }
}

Although exception was thrown in LibraryInternal() method console output will be following:
at ConsoleApplication6.Program.LibraryAPI() in D:\Users\andrii.khymenko\Development\ConsoleApplication6\ConsoleApplication6\Program.cs:line 35
at ConsoleApplication6.Program.ClientMethod() in D:\Users\andrii.khymenko\Development\ConsoleApplication6\ConsoleApplication6\Program.cs:line 19

By changing “throw ex;” to “throw;” in LibraryAPI() stack trace in console output will change to:
at ConsoleApplication6.Program.LibraryInternal() in D:\Users\andrii.khymenko\Development\ConsoleApplication6\ConsoleApplication6\Program.cs:line 41
at ConsoleApplication6.Program.LibraryAPI() in D:\Users\andrii.khymenko\Development\ConsoleApplication6\ConsoleApplication6\Program.cs:line 35
at ConsoleApplication6.Program.ClientMethod() in D:\Users\andrii.khymenko\Development\ConsoleApplication6\ConsoleApplication6\Program.cs:line 19

This difference in behavior has simple explanation: MSIL has two instructions “throw” and “rethrow” while C# has only one keyword “throw”. When code gets compiled all “throw;” lines end up with “rethrow” in MSIL which will keep original stack trace.

Virtual Functions in Constructors Trap

In .NET calling virtual function in constructor of a class is a bit tricky. While one can expect that implementation from current class will be invoked, runtime actually always calls implementation of the function from the most derived class of all possible. So if virtual method in child class doesn’t call implementation from parent one can get trapped and initialization will be done incorrect.

For example, using BaseClass and DerivedClass provided below

		class BaseClass {
			public string DefaultName {
				get {
					return _defaultName;
				}
			}
			protected string _defaultName;

			public BaseClass() {
				InitializeDefaults();
			}

			public virtual void InitializeDefaults() {
				_defaultName = "BaseClass";
			}
		}

		class DerivedClass : BaseClass {
			public DerivedClass() {
			}

			public override void InitializeDefaults() {
			}
		}

when creating instances of the classes DefaultName will be different:
BaseClass baseClass = new BaseClass();
// baseClass.DefaultName: "BaseClass"

DerivedClass derivedClass = new DerivedClass();
// derivedClass.DefaultName: null

How To: Unit Test a Singleton

Unit testing a Singleton is not a trivial task because each test needs untouched Singleton object to keep all the tests isolated. One way to achieve this is to recreate underlying singleton object using reflection during test setup or teardown as described by Jonathan de Halleux and Omer van Kloeten.

But I think that a better way is to extract implementation from singleton into a separated class. This way we’ll have a class that contains all the logic to be tested and another class used to wrap it into a singleton.

public class LoadBalancer {
	internal LoadBalancer() {
	}

	// LoadBalancer class implementation goes here...
}

public sealed class LoadBalancerSingleton {
	private static readonly LoadBalancer _instance = new LoadBalancer();

	private LoadBalancerSingleton() {
	}

	public static LoadBalancer Instance {
		get {
			return _instance;
		}
	}
}

Using InternalsVisibleTo attribute in this assembly we can allow test project to perform needed unit testing. Although technically it is possible to create another instance of the LoadBalancer class inside this assembly comments on constructor and common sense should prevent such a situation.

So to my mind it’s a good alternative to reflection approach.

How To: Save XmlDocument without Declaration

Normally saving XmlDocument leads to xml declaration at the beginning of file. In case it is desirable to omit it, XmlWriterSettings comes to help:

XmlDocument doc = new XmlDocument();
// Do with document whatever is needed...

// Save xml document without xml declaration.
XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.OmitXmlDeclaration = true;
using (XmlWriter writer = XmlWriter.Create(@"\omit.xml", writerSettings)) {
	doc.Save(writer);
}

How To: Check Whether String is a Valid Path String

Sometimes it’s needed to verify if given string with path is valid in terms of syntax to make sure that we can work with it (meaning it doesn’t contain symbols not allowed in path). This can be done pretty simply:

bool isValid = (path2Check.IndexOfAny(Path.GetInvalidPathChars()) == -1);

The Most Unexpected Explanation of Delegates I’ve Ever Read

Once upon a time, in a strange land south of here, there was a worker named Peter. He was a diligent worker who would readily accept requests from his boss. However, his boss was a mean, untrusting man who insisted on steady progress reports. Since Peter did not want his boss standing in his office looking over his shoulder, Peter promised to notify his boss whenever his work progressed.

To read full story follow the link .NET Delegates: A C# Bedtime Story.

I’m Tweeting

Follow

Get every new post delivered to your Inbox.