Category Archives: Programming Basics

Disposing Resources

When you are working with managed resources in C#. you can usually let the Garbage Collector deal with tidying up after you. Memory allocation problems that are familiar in the past with languages such as C are dealt with for you.

The Garbage Collector is not magic. First off you don’t usually control when garbage collection occurs. The Framework will initiate collection whenever it thinks it’s necessary. Sometimes you’ll go a long time between collections, but as resources begin to become scarce, it will happen more often.

You can call a forced collection, but it’s rare that this is  a good idea. The Garbage Collector itself will manage when collections need to occur. Forcing multiple early collections is almost always worse than letting the collection happen automatically.

The Garbage Collector cannot deal with unmanaged resources. The most common of these that you will encounter are related to database connections, and file access.

You should do two things when dealing with unmanaged resources. First off, wrap them in using statements. This ensures that the dispose method is called once you are finished with the resource.

The second thing to do is to make sure that your classes implement the IDisposable interface. This means that when the Dispose() method is called you have a chance to clean up your unmanaged resources, to prevent any memory leaks and ensure that the Garbage Collector can do it’s job.

There are a lot of further complexities to the Garbage Collection and memory management, most of the time you won’t have to worry too much about them, but it’s good to know the basics for the times you do.


Extension Methods

Extension methods in C# are a way to expand the functionality of a class without creating new derived types.

You need to be careful when you use an extension method, once you start it’s very easy to just make everything into an extension.

Try to be controlled, only make an extension method if you really need to. Usually this is to add functionality to classes you do not control the source code to. You also want to only add an extension that makes sense for the whole problem domain. Don’t extend int to give values relating to time, or other such oddness.

The most common modern use is to create new Html Helpers in MVC.

namespace MyProject.Extensions
  public static class HtmlHelperExtensions
    public static string BeHelpful(this HtmlHelper helper)
      return "I'm Helping";

To use this extension in your view, you need to make sure that the namespace it’s in is included in the ~/Views/web.config file. You will also need to reference the namespace with a using directive.

@using MyProject.Extensions

If you want to pass additional data to your helper, then you would include these parameters in the method definition

public static string ShortenString
  (this HtmlHelper helper, string value)
      value.Length() > 10 ? value.Substring(0, 10) : value;

One further thing to consider, when creating extensions you cannot override an existing method, if you attempt to do this it will not work, the original method will always be called.

So, use extension methods carefully, otherwise you will clutter up your code. They are useful, but not a cure to all your problems.

Factory Pattern

When we are designing systems we can make use of a variety of deign patterns. They are valuable for many reasons, not least that using a common and understood way of designing something means that it will be easily understood by people familiar with the pattern.

The Factory Design pattern can be used when you have a large number of similar objects (so can be referred to through a common interface or abstract class), and where you wish to hide the instantiation logic from the calling class.

Consider a simple drawing program. You might want to create one of a large number of types of shape, square, circle, triangle etc.

We can use a Factory class to return an instance of the type of shape we want:

public abstract class Shape
  public abstract Shape createShape();

public class Square : Shape
  public Square() {}

  public override Shape createShape()
    return new Square();

public class ShapeFactory
  Dictionary<string, Shape> registeredShapes;

  private static readonly ShapeFactory instance = new ShapeFactory();

  private ShapeFactory()
    registeredShapes = new Dictionary<string, Shape>();
    var Shapes = from b in Assembly.GetExecutingAssembly().GetTypes()
                 where b.IsSubclassOf(typeof(Shape))
                 select b;

    foreach (var type in Shapes)
      var s = type.GetConstructor(System.Type.EmptyTypes).Invoke(null);
      registeredShapes.Add(type.Name, (Shape)s);

  public static ShapeFactory Instance
       return instance;

  public Shape createShape(string shapeName)
    return ((Shape)registeredShapes[shapeName]).createShape();

From this we can simply call ShapeFactory.Instance.createShape(“Square”); and this will give us a new instance of the Square object.

As we expand to define extra types of shape, we won’t need to alter the Factory, we can just implement the new shape, it will be discovered automatically, thanks to the use of reflection.

Whilst this is clearly a simple example, where we are just creating and return the objects, it should be easy to see that we can use much more complicated objects. We would hide all the creation logic inside each type, and use the factory to pass an fully created concrete instance whenever one is required.

Interfaces and Abstract Classes

In .NET we can think of Interfaces as a contract for behaviour.

Any class that implements the Interface will be required to implement all of the methods defined in the interface. An Interface can only have a list of methods to be implemented by inheriting classes, it can contain no implementation detail.

A class can implement many Interfaces.

Interfaces can be used by many kinds of class. You might create an IFlyable interface, with a single method, Fly. This could be implemented by a Plane class, a Helicopter class a Bird class and so on. There is little to link these class types, but they all Fly.

An abstract class is similar to an Interface, but has a number of important differences. Where we consider the Interface as a contract for behaviour, an abstract class will define what a set of objects is.

An abstract class would be a base for many similar classes. It can contain methods and state data that cannot be captured in an Interface. You could create an Animal class, and contain properties for Height and Weight. You could also add a method Breathe, which would cause the animal to breathe. In the Animal class you can have a simple implementation of the Breathe method, and you can override it in complex child cases (such as a Fish class).

A class can only inherit from a single abstract class.

So, Interfaces describe what an object can do, abstract classes describe what an object is.