Showing posts with label language. Show all posts
Showing posts with label language. Show all posts

Sunday, 3 May 2015

Implicit vs. Explicit Interface Implementation

One feature of C# that I find useful is the support of implicitly or explicitly implementing interfaces. For example, if we have a simple interface such as the following:
public interface IDoSomething
{
    void DoIt();
}
You are probably already aware that we can implicitly implement the interface with code like:
public class MyClass : IDoSomething
{
    public void DoIt()
    {
        throw new NotImplementedException();
    }
}
We can use the implementation like:
MyClass myClass = new MyClass();
myClass.DoIt();
If MyClass is to explicitly implement the interface, the MyClass implementation would look like:
public class MyClass : IDoSomething
{
    void IDoSomething.DoIt()
    {
        throw new NotImplementedException();
    }
}
Notice the two differences.
  1. The access modifier has been dropped from the DoIt method signature
  2. The DoIt method name is now qualified with the interface name
So how does this now affect how we use MyClass? Well, you can no longer call the DoIt method on a direct instance of MyClass, you are now forced to code to the interface to access the DoIt method. So our previous code which instantiates MyClass and calls DoIt will no longer compile. Instead you will need to "explicitly" work with an instance of the interface to access the DoIt method. One example would be by declaring the type of the object to be the interface, like the following:
IDoSomething myClass = new MyClass();
myClass.DoIt();
Or you could cast the MyClass instance back to its interface to call the DoIt method, as shown in the following snippet:
MyClass myClass = new MyClass();
((IDoSomething) myClass).DoIt();
So, what are the benefits of explicitly implementing an interface?
  • As the implementer of a class, you can try to force good practice on clients by making them code to an interface
  • As a consequence of the point above, you can reduce tight coupling in your code as it shouldn't be using concrete implementations directly
  • If you are implementing two interfaces which have the same method signatures, or a method signature in an interface clashes with one already visible in your class, you can separate the two methods

Saturday, 2 May 2015

Microsoft Exam 70-483: Programming in C#

Earlier this week I took and passed the Microsoft 70-483 exam. In this post, I'll provide some insight into my preparation.

The 70-483 exam tests your knowledge on the C# programming language and the .NET framework. In this case, it was C# 5 and the .NET Framework version 4.5. By passing this exam, you earn the Microsoft Specialist certification.
 
The official Microsoft page for the exam can be viewed by clicking on this link. I took the exam in the UK. It should be noted that the 70-483 exam is also the first exam on the path for the MCSD Windows Store Apps certification, which is ultimately the certification that I'm aiming for. 
 
As described on the official 70-483 exam page, the exam is broken down into four main areas:
  • Managing program flow
  • Creating and using types
  • Debugging applications and implementing security
  • Implementing data access

Under each of these topics on the exam page, you get a detailed breakdown of what is covered. There is a plethora of resources on the web that you can use to prepare for this exam (blogs, MSDN, PluralSight etc.). I recommend watching the exam prep video on the exam page first - this sets the scene in more detail and gives you a better idea about the topics covered on the exam.
 
As the two guys mention on the Microsoft prep video, there is no substitute for actual practice. At the beginning of my preparation, I created a blank console application in Visual Studio and added to this as I revised various topics. I wrote a method for each particular language construct or .NET framework class that I wanted to further understand. In each method, I practiced using a particular construct/class by referring to the MSDN site for the topic. I found this approach useful in clarifying how something works - the code produced also served as a useful reminding aid when the exam date got closer (the brain recalled those "eureka" moments that I had when writing the code). LINQPad is also a useful tool for practicing.
 
I found the official Microsoft exam reference book by Wouter de Kort useful (Amazon link here). Although the book shouldn't be used as a definitive resource, it serves as a useful aid in introducing various topics which you then should build upon with your own further research. I particularly found the multithreading, cryptography and managing assemblies sections of the book a worthwhile read.
 
I also bought the practice tests from MeasureUp. The practice tests were useful to get a feel for question formats - which are a mixture of multiple choice (sometimes with more than one correct choice) and drag and drop type questions. You can also loosely simulate test conditions by running the MeasureUp tests in "certification mode" - meaning that you are timed and unable to see the answers as you progress in the test. Note that the actual exam format/time can differ compared to the MeasureUp practice certification mode tests.
 
Finally, ensure you read the website of the test centre. In the UK, Microsoft has appointed the PearsonVUE test centres. I found the videos on the PearsonVUE website useful in telling me what to expect on the day (security procedures, the software used for the exam itself and what I need to bring with me on the exam day).
 
If you're taking this exam, all the best and feel free to leave a comment about your experiences!

Wednesday, 15 April 2015

C# How To: Using Implicitly Typed Arrays

Implicitly typed arrays allow the C# compiler to determine the most appropriate type for an array. The selected type is based on the values you initialise the array with. This useful feature was introduced in C# 3.0.
var intArray = new [] { 1, 2, 3 };
var stringArray  = new [] { "hello""world"null };
var nullableIntArray = new [] { 1, (int?)2, 3 };

Console.WriteLine(intArray.GetType());
Console.WriteLine(stringArray.GetType());
Console.WriteLine(nullableIntArray.GetType());

// Following results in a compile-time error:
//    "No best type found for implicitly-typed array"
var notGoingToWorkArray = new [] { "hello", 1, 2f };

Friday, 16 January 2015

C# How To: CSV to List or List to CSV

The following code snippet shows how to convert from a CSV string to a List using the string class Split method.

const string ColoursCsv = "red,blue,green,yellow";
                        
List<string> coloursList = ColoursCsv.Split(',').ToList();

The following code snippet shows how to convert from a list to a CSV string using the string class Join method.

List<string> coloursList = new List<string> { 
    "red"
    "blue"
    "green"
    "yellow" 
};

string coloursCsv = string.Join(",", coloursList);

C# How To: Convert to Convert String to Int

To convert from a string to an integer type you can use the Convert class as shown in the code snippet below. The Convert class contains a large number of static methods which allow you to convert from one type to another.

string numberString = "1985";
int number = Convert.ToInt32(numberString);

Monday, 12 January 2015

C# How To: Start a Program/Process

To start a program in C#, you can use the Process class. The Process class has a static method called Start which accepts a filename as a parameter. The example below shows how easy it is to start Microsoft Notepad from a C# application. Remember to include the "using System.Diagnostics;" directive at the top.

const string ProgramPath = "Notepad";

Process.Start(ProgramPath);

Note that if you need to start a program which accepts command line arguments, then you can use an overload of the Start method which accepts a ProcessStartInfo object. The following snippet shows how to open a file within notepad from your C# application.

const string ProgramPath = "Notepad";

Process.Start(new ProcessStartInfo
    {
        FileName = ProgramPath,
        Arguments = @"C:\WriteTest.txt"
    }
);

Sunday, 11 January 2015

C# How To: Create Text File And Write To It

Continuing with my new C# "how-to" theme, the code snippet below shows how to create a text file and write content to it using the StreamWriter class. Remember to add the "using System.IO;" directive at the top. Note that there is a StreamWriter constructor which supports a Boolean parameter "append" - if you pass true for this parameter and the file already exists, the StreamWriter will append content to the file rather than overwrite the existing content.

const string TextFilePath = @"C:\WriteTest.txt";

using (StreamWriter writer = new StreamWriter(TextFilePath))
{
    writer.WriteLine("Hello, world");
    writer.WriteLine("Bye, world");
}

C# How To: Read a Text File

This is the first of a series of C# "how to" posts. The following C# code snippet shows how to read a text file line-by-line using the StreamReader class. Remember to add the "using System.IO;" directive as this is the namespace which the StreamReader class is in.

const string TextFilePath = @"C:\ReadTest.txt";

using (StreamReader reader = new StreamReader(TextFilePath))
{
    string currentLine;

    while ((currentLine = reader.ReadLine()) != null)
    {
        Console.WriteLine(currentLine);
    }
}

Saturday, 22 November 2014

Short-circuit Boolean Evaluation

A useful but often not thought about feature is that many programming languages, including C#, support short-circuit evaluation of Boolean expressions. For example, in the following logical AND condition:

if (OperandOne && OperandTwo) 
{    
}

OperandTwo is only evaluated if OperandOne equals the Boolean value of true. If OperandOne's value is false, then the entire condition evaluates to false regardless of the value of any other operand in the condition (basic boolean algebra). Hence, there is no reason to continue evaluating the subsequent operands. This functionality is known as short-circuiting. You can confirm this language feature in C# with some basic code:

void Main()
{
    if (MethodOne() && MethodTwo())
    {
    }
}

bool MethodOne()
{
    Console.WriteLine("MethodOne: I got evaluated!");
    return false;
}

bool MethodTwo()
{
    Console.WriteLine("MethodTwo: I got evaluated!");
    return true;
}

After executing the code above, you'll see that the Console.WriteLine call in MethodOne only gets called. Short-circuit evaluation also works for the logical OR operator. Let's change the condition in the above code snippet to look like:

if (MethodOne() || MethodTwo())
{
}

If you now execute the code, you'll see that both of the Console.WriteLine calls in MethodOne and MethodTwo get called. However, if you now change MethodOne to return true and re-execute, you'll see that C#'s short-circuit evaluation kicks-in and only the Console.WriteLine in MethodOne gets executed.

Short-circuit evaluation gives you, as the programmer, a neater way to express your code. For example, without short-circuit evaluation, you wouldn't be able to construct conditions such as:

if (person != null && person.Age > minimumAge)
{
}

In this condition, a check is first made to ensure the person object isn't null before we go ahead and try to access the Age property on the object. If the person object is null, then the short-circuiting kicks-in and prevents the incorrect access of the Age property (which would result in a NullReferenceException to be thrown).

A lesser known nuance of C# is that short-circuit evaluation can be bypassed as a side effect of using the bitwise operators & and | without losing the semantics of the logical operation. For example, if we reuse our code snippet from earlier and make a minor adjustment to the condition to use the bitwise AND operator, we'll have:

void Main()
{
    if (MethodOne() & MethodTwo())
    {
    }
}

bool MethodOne()
{
    Console.WriteLine("MethodOne: I got evaluated!");
    return false;
}

bool MethodTwo()
{
    Console.WriteLine("MethodTwo: I got evaluated!");
    return true;
}

After executing the snippet above, you'll now see that both the Console.WriteLine in each of MethodOne and MethodTwo get called despite MethodOne (the first operand) returning false. Using a single & over && does not affect the semantics of the logical AND operator - so the code within the braces of the if-condition would still not get executed in this case (as the entire expression still evaluates to false). However, the key thing to note is that all operands are evaluated when bypassing short-circuit evaluation. Similar to the single & operator, short-circuit evaluation is also bypassed when using a single | (bitwise OR) without losing the semantics of OR.

It is generally advised not to bypass short-circuit evaluation but I find that it is important to be aware of it to catch bugs. In the past, I have noticed on several occasions that subtle bugs were introduced where a developer has used a single & and one of the operands in the expression had a side effect (e.g. a method that performs an action). Perhaps they came from a non-short-circuit-featured language where the single character versions of && and || are used to express logical AND and OR?. Take the following code snippet as an example:

if (person.HasChanges & _repository.UpdatePerson(person))
{
    ...
}

In this case, the UpdatePerson method will always be called, even when the person object states that it has no changes. This is a subtle bug which can easily be missed. Nevertheless, it is fixed by using the && operator to make use of short-circuit evaluation!

Sunday, 7 July 2013

C# How To: Implement the Soundex Algorithm

I caught the end of a conversation about the Soundex algorithm at work the other day which inspired me to write an implementation of it in C#. If you are not familiar with what Soundex is then the Wikipedia article on Soundex is a good place to start. I first came across this algorithm in a Natural Language Processing module during my university education. In a nutshell, when the Soundex algorithm is applied to a word, a Soundex Code is produced as output. Words that differ in spelling but sound the same (homophones) should produce the same Soundex Codes. For instance, "to" and "two" are spelt differently, but sound the same and therefore produce the same Soundex Code of "T000".

This is a useful little algorithm and I particularly like it for its simplicity and the fact that the heuristics used in the algorithm work well in most cases (one limitation of Soundex is that it falls short of covering words that sound the same but have a different first letter, e.g. "site" and "cite" produce different Soundex codes). Soundex is useful when writing search functionality where you want to account for misspellings in the users query. It's worth pointing out that SQL Server natively supports Soundex (see the Soundex function in T-SQL, for example).

My C# implementation is below - I opted to implement it in a static class that exposes one public method "For". The example source code is available on GitHub - https://github.com/rsingh85/SoundexExample

public static class Soundex
{
    public static string For(string word)
    {
        const int MaxSoundexCodeLength = 4;

        var soundexCode = new StringBuilder();
        var previousWasHOrW = false;

        word = Regex.Replace(
            word == null ? string.Empty : word.ToUpper(),
                @"[^\w\s]",
                    string.Empty);

        if (string.IsNullOrEmpty(word))
            return string.Empty.PadRight(MaxSoundexCodeLength, '0');

        soundexCode.Append(word.First());

        for (var i = 1; i < word.Length; i++)
        {
            var numberCharForCurrentLetter =
                GetCharNumberForLetter(word[i]);

            if (i == 1 &&
                    numberCharForCurrentLetter ==
                        GetCharNumberForLetter(soundexCode[0]))
                continue;

            if (soundexCode.Length > 2 && previousWasHOrW &&
                    numberCharForCurrentLetter ==
                        soundexCode[soundexCode.Length - 2])
                continue;

            if (soundexCode.Length > 0 &&
                    numberCharForCurrentLetter ==
                        soundexCode[soundexCode.Length - 1])
                continue;

            soundexCode.Append(numberCharForCurrentLetter);

            previousWasHOrW = "HW".Contains(word[i]);
        }

        return soundexCode
                .Replace("0"string.Empty)
                    .ToString()
                        .PadRight(MaxSoundexCodeLength, '0')
                            .Substring(0, MaxSoundexCodeLength);
    }

    private static char GetCharNumberForLetter(char letter)
    {
        if ("BFPV".Contains(letter)) return '1';
        if ("CGJKQSXZ".Contains(letter)) return '2';
        if ("DT".Contains(letter)) return '3';
        if ('L' == letter) return '4';
        if ("MN".Contains(letter)) return '5';
        if ('R' == letter) return '6';

        return '0';
    }
}
Example:

// Both lines below output R100
Console.WriteLine(Soundex.For("Ravi"));
Console.WriteLine(Soundex.For("Ravee"));

Wednesday, 20 February 2013

Implementing the Chain of Responsibility Design Pattern

Earlier this week I made use of the Chain of Responsibility design pattern to solve a fairly straight-forward problem. I've always been careful when trying to apply design patterns, it's easy to get carried away and try to force a design pattern to a problem that doesn't really require it. In this case, I felt it was justified and hopefully you'll think the same!

The Context

I'll give some context to the problem before we go into exactly what the Chain of Responsibility pattern is. I was working on a HTTP service (built on ASP.NET Web API) which had an API controller action that accepted requests for some data stored in a persistent repository. My requirement was to inspect the incoming request object, and depending on certain characteristics of the request, log the request object data to zero or many different output locations. This is to enable reporting on the types of requests that the service receives. The output locations were disparate data stores such as an XML file, Excel file and SQL Server Database. The key point was that to log the request I had to inspect the content of the request, and depending on some criteria, log it to none or certain data stores. Furthermore, certain requests had to be ignored and therefore not logged.

Chain of Responsibility

When I read this requirement I knew immediately there was a design pattern for this type of problem. I had taken an Object-Oriented design pattern course at university around six years ago but couldn't quite remember the name of the pattern. After having a quick look on the GoF website, I eventually found it - Chain of Responsibility (CoR). CoR is a software design pattern that has been classified into the "behavioral" category of patterns - these are patterns that broadly deal with objects interacting with other objects. The idea is that you have multiple handler objects chained together just like a linked list data structure. An incoming request object is passed over to the first handler in the chain, the handler (depending on its "responsibility"), inspects the request and can either:
  1. Handle the request and not pass the request down the chain of handlers
  2. Handle the request but still pass the request down the chain of handlers
  3. Not handle the request and pass the request down the chain to the next handler
Note that before a handler sends the request object down the chain, it is also responsible for checking if it is actually linked to another handler. If a handler isn't linked to another handler, it is the last handler in the chain and therefore consumes the request.

Applying CoR to the Problem

In my case, the incoming data request to the API was my CoR request that required "handling" from a logging perspective. I implemented a separate concrete logging handler class for each of the concrete data stores (XML, Excel and SQL Server). Each logging handler inspected the request and logged the request if it matched the criteria for the handler before passing the request to the next handler. Therefore, in my case, the CoR handler behaviour corresponded to point two above.

The Implementation

Note that I've stripped down the code below (especially for each concrete handler) so that it is easier to see what's going on from a design pattern perspective.

The first step was to write an abstract base handler that defined the behaviour that each of my handlers will support. The HandlerBase class below is generic enough to be reused in any case where you require a CoR implemented. The single type parameter "TRequest" is the type of the object that will go through your chain (can be any .NET type).
public abstract class HandlerBase<TRequest>
{
    public HandlerBase<TRequest> Successor
    { 
        protected get; 
        set; 
    }

    public abstract void HandleRequest(TRequest request);
}
The HandlerBase class has one property, which allows users of a handler to set a successor to this handler (the next handler in the chain) and it has an abstract method that all derived classes will need to implement - HandleRequest. You will see further below how we use the Successor property when setting up our chain, and how each concrete handler (a class that derives from HandlerBase) uses the HandleRequest method on its successor to pass the request down the chain.

Next, I implemented each of my concrete handlers - that is, a handler for logging to an XML document, Excel document and SQL server.
public class LogRequestToXmlHandler : HandlerBase<ApiDataRequest>
{
    public override void HandleRequest(ApiDataRequest request)
    {
        if (request.Foo == Something && request.Bar == SomethingElse)
            // Log request to xml document

        // Pass on the request to the next handler, if any
        if (base.Successor != null)
            base.Successor.HandleRequest(request);
    }
}
Notice how the concrete handler LogRequestToXmlHandler derives from HandlerBase and passes the type of the object that is going through the chain - ApiDataRequest. Also notice that because we're inheriting from an abstract base class containing one abstract method - we're forced by the compiler to override the HandleRequest method. This method accepts one parameter, the request object. It is in this method that you will place any specific handling logic for the request object - I've added some pseudo-code to demonstrate this. The last couple of lines inspect the Successor property (inherited from the base class), if it isn't null - then we call the HandleRequest on it, thus passing our request down the chain. If Successor returns null, then the current handler is the last in the chain and we do nothing - effectively consuming the request. For completeness, the other handlers are below.
public class LogRequestToExcelHandler : HandlerBase<ApiDataRequest>
{
    public override void HandleRequest(ApiDataRequest request)
    {
        if (request.Foo == Something && request.Bar == SomethingElse)
            // Log request to excel document

        if (base.Successor != null)
            base.Successor.HandleRequest(request);
    }
}

public class LogRequestToDbHandler : HandlerBase<ApiDataRequest>
{
    public override void HandleRequest(ApiDataRequest request)
    {
        if (request.Foo == Something && request.Bar == SomethingElse)
            // Log request to database

        if (base.Successor != null)
            base.Successor.HandleRequest(request);
    }
}
Now that we have our handlers, the final step is to setup our chain so that it's ready to handle requests. The code below shows how the handlers are chained together.
HandlerBase<ApiDataRequest> logToXmlHandler
    = new LogRequestToXmlHandler();

HandlerBase<ApiDataRequest> logToExcelHandler
    = new LogRequestToExcelHandler();

HandlerBase<ApiDataRequest> logToDbHandler
    = new LogRequestToDbHandler();

logToXmlHandler.Successor = logToExcelHandler;
logToExcelHandler.Successor = logToDbHandler;
The first step above was to initialise each handler that will be going into the chain. We then use the Successor property to chain the three handlers together. The beauty of using this pattern is that you can chain however many handlers you want and even make the chain configurable so that it is setup at runtime depending on some settings in a config file.

Now, when a new request came through my API, it was a simple case of invoking the HandleRequest method on the first handler in the chain and passing the ApiDataRequest object through as a parameter. This sent the object down the chain, allowing each log handler to inspect it and decide whether to log it to their individual outputs.
logToXmlHandler.HandleRequest(request);
* Update *

One thing that I missed in this post and is worth mentioning is a scenario where you don't want each concrete handler to decide whether to pass the request on down the chain. In this case, the request would go to every handler in the chain regardless. One way to accomplish this is to update the HandlerBase class as follows:
public abstract class HandlerBase<TRequest>
{
    public HandlerBase<TRequest> Successor
    { 
        protected get; 
        set; 
    }

    public void HandleRequest(TRequest request)
    {
        Handle(request);

        if (Successor != null)
            Successor.HandleRequest(request);
    }

    protected abstract void Handle(TRequest request);
}
The updated HandlerBase now implements a public HandleRequest method which first delegates the handling logic to an abstract method (Handle) which will be overridden by a concrete handler. Once a request has been handled, a test is made to check if there is a successor and if there is, then the request is passed on. What this now means is that each concrete handler will implement just one method, Handle, and not need to worry about whether to pass the request on or not - that is done automatically in the HandleRequest method. An example concrete handler is below:
public class LogRequestToXmlHandler : HandlerBase<ApiDataRequest>
{
    protected override void Handle(ApiDataRequest request)
    {
        // Check request and log it, if required
    }
}

Friday, 5 October 2012

C# How To: Convert Integer to Base Binary, Octal, Denary or Hexadecimal

A few weeks ago I had a requirement to convert an Int32 value (base 10 or decimal) to its binary representation as a string. I encapsulated the logic to convert the decimal number to a binary string in a method. I used the base 10 to base 2 algorithm where the decimal number is continiously divided by two until it becomes zero. Within the iteration, the modulo two of the number is then appended to the output binary string. At the time of writing that code, it seemed like the best way to go about it, and because it was neatly encapsulated in a method, I knew I could swap out the implementation at a later date without much hassle.

Today, I came across an overload of the Convert.ToString method which surprisingly accepted a parameter called toBase. I wish I had come across this earlier... The overload accepts the bases 2, 8, 10 or 16 and throws an ArgumentException if one of these are not passed in. Examples are below:

Console.WriteLine("{0}", Convert.ToString(10,2));  // Outputs "1010
Console.WriteLine("{0}", Convert.ToString(10,8));  // Outputs "12"
Console.WriteLine("{0}", Convert.ToString(10,10)); // Outputs "10"
Console.WriteLine("{0}", Convert.ToString(10,16)); // Outputs "a"
Console.WriteLine("{0}", Convert.ToString(10,3));  // Throws ArgumentException

Friday, 10 February 2012

C# How To: Write a Fluent API

I've seen a number of API's now that utilise a "fluent" interface (e.g., Fluent NHibernate, Moq etc.). So far, I've had mixed feelings about it. If you're not familiar with what a fluent interface is, then Martin Fowler's post on this subject is a good starting point. By following a fluent design, you get some neat looking "client-side" code that is almost self-describing. The following example models a real-world person and exposes a fluent interface.

public class Person
{
    public string FirstName { get; private set; }
    public string Surname { get; private set; }

    private Person() { }

    public static Person New()
    {
        return new Person();
    }

    public Person SetFirstName(string firstName)
    {
        this.FirstName = firstName;
        return this;
    }

    public Person SetSurname(string surname)
    {
        this.Surname = surname;
        return this;
    }

    public override string ToString()
    {
        return string.Format(
            "I am {0} {1}",
                this.FirstName,
                    this.Surname);
    }
}
As the code snippet shows, each setter method in the Person class returns a reference to the "current" object (think context/state). This is important as it permits users of the class to chain method calls on the object, with each invocation returning an up-to-date state of the original object. For example, we can create an instance of Person and then set its state in one single C# statement:

var person = Person.New()
    .SetFirstName("Ravi")
        .SetSurname("Singh");
This looks neat and is very readable. Without a fluent interface, you may have code that looks somewhat like:

var person = new Person();
person.FirstName = "Ravi";
person.Surname = "Singh";
Of course, you could use the object initialiser syntax or pass the names through to an appropriate constructor, but that's not the point. The point is that you don't get the same readability or fluentness that you get using method chaining. If your methods are named properly, then using the fluent technique makes reading your code closer to reading a sentence in natural language.

I personally prefer the fluent version. Earlier in the post, I mentioned that I had a mixed feeling - this mainly stems from the fact that it becomes difficult to debug code that uses a fluent interface. For example, if you have a statement in which a number of method calls are chained on an object, it's difficult to see the intermediary values returned by each method unless you step into each method call. This can be a bit of a pain when debugging. Other than this one problem, I've enjoyed working with fluent-based API's and will strive to write classes in a more "fluent" way.

Wednesday, 21 December 2011

C# How To: Bit Flags

I use an Enumeration type whenever I need to define a set of named constants that can be assigned to a variable. Enums are easier on the brain than magic numbers and they ensure that valid values are being used throughout your code (you also have the added compile-time checking advantage).

The following enum models the months in the year:

enum Months { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec }
To use the above enum, you define a variable of the enum type that can be assigned a value from the enumeration:

Months christmasMonth = Months.Dec;
The variable christmasMonth now represents the month December. It's worth knowing that by default, each enum value is assigned an integer value based on its order of definition (the underlying type of an enumeration value is actually an integer). In this example, the value Months.Jan is assigned the integer 0 and Months.Dec is assigned the int 11. These integer values can be overridden as we will see further below.

Sometimes, it makes sense to be able to assign multiple enum values to a single variable. For example, it would be nice to be able to assign multiple Month enum values to a Months variable called summerHolidayMonths. This is possible using the bit flag technique.

To create a bit flags enum, you assign the attribute [System.FlagsAttribute] to the enum definition and sequentially assign values of the power two (starting from zero) to each enumeration value:

[System.FlagsAttribute]
enum Months
{
     Jan = 0x0,   //000000000001 (base 2) 0 (base 10)
     Feb = 0x1,   //000000000010 (base 2) 1 (base 10)
     Mar = 0x2,   //000000000100 (base 2) 2 (base 10)
     Apr = 0x4,   //000000001000 (base 2) 4 (base 10)
     May = 0x8,   //000000010000 (base 2) 8 (base 10)
     Jun = 0x10,  //000000100000 (base 2) 16 (base 10)
     Jul = 0x20,  //000001000000 (base 2) 32 (base 10)
     Aug = 0x40,  //000010000000 (base 2) 64 (base 10)
     Sep = 0x80,  //000100000000 (base 2) 128 (base 10)
     Oct = 0x100, //001000000000 (base 2) 256 (base 10)
     Nov = 0x200, //010000000000 (base 2) 512 (base 10)
     Dec = 0x400  //100000000000 (base 2) 1024 (base 10)
}
Thus, the enum value Months.May, can now also be represented by the bit pattern "000000010000".

By thinking in terms of bits, we can now use the bitwise logical OR operator in C# to assign multiple enumeration values to a single enum variable, for example:

Months summerHolidayMonths = Months.May | Months.Jun | Months.Jul | Months.Aug;
summerHolidayMonths now represents the months May, June, July and August.

By logical OR'ing each value, we're storing the bit pattern "000011110000" in the summerHolidayMonths variable. As stated, this pattern was arrived at by bitwise OR'ing the bit patterns of each of the summer month enum values:

 Months.May = 000000010000
 Months.Jun = 000000100000
 Months.Jul = 000001000000
 Months.Aug = 000010000000
              ------------
Logical OR  = 000011110000


Clever... but how do we know if a particular month is stored in the summerHolidayMonths variable? We can use the bitwise logical AND operator like so:

bool isJuneInSummerMonths = (summerHolidayMonths & Months.June) == Months.June;
We can also remove a month from the summerHolidayMonths by computing the bitwise logical XOR of the variable with the enum value to remove. In the example below, we're removing the month May from summerHolidayMonths:

summerHolidayMonths = summerHolidayMonths ^ Months.May;
I'll leave it to you to apply the XOR on the months to see that it does really work!

Next time you define an enumeration, give some thought as to whether it makes sense to allow users of your enum to store multiple enumeration values in the enumeration variable - if it does make sense, then use bit flags!

Monday, 19 December 2011

C# How To: Log to File

Over the past few weeks, I've needed to write a number of small "throw-away" console applications. These applications processed a large amount of data and there was a need to log progress. I wrote the following fairly reusable file logging class which someone may find useful. Alternatively, I'm also interested to get some feedback on whether it could be improved in any way, so feel free to comment on this one.

public class FileLogger
{
    private static FileLogger singleton;
    private StreamWriter logWriter;

    public static FileLogger Instance
    {
        get { return singleton ?? (singleton = new FileLogger()); }
    }

    public void Open(string filePath, bool append)
    {
        if (logWriter != null)
            throw new InvalidOperationException(
                "Logger is already open");

        logWriter = new StreamWriter(filePath, append);
        logWriter.AutoFlush = true;
    }

    public void Close()
    {
        if (logWriter != null)
        {
            logWriter.Close();
            logWriter = null;
        }
    }

    public void CreateEntry(string entry)
    {
        if (this.logWriter == null)
            throw new InvalidOperationException(
                "Logger is not open");
        logWriter.WriteLine("{0} - {1}",
             DateTime.Now.ToString("ddMMyyyy hh:mm:ss"),
             entry);
    }
}
Simple example of usage (I'd wrap this in a try/catch/finally where the finally calls the close method):

FileLogger.Instance.Open(@"C:\MyLog.log", false);
FileLogger.Instance.CreateEntry("Hello, world!");
FileLogger.Instance.Close();