The difference between a using statement inside a namespace and out

I honestly didn’t think that there was a difference between the locations of your using statements in C#, be they in or outside of a namespace, but I just ran into a strange situation where the difference will cause a build error. If you’re wondering what I mean by “in a namespace” please examine the following code.

namespace Example.Program
{
      using Example.Sample;
 
      class Program
      {
            static void Main(string[] args)
            {
                  Something s = new Something();
            }
      }
}
This is legitimate code and will compile just fine. So you can either have your using statements outside of a namespace and in the same file or inside of the namespace. There is a slight difference however, inside of your namespace your using statements may interpret parts of the following namespace as classes while outside it will always resolve as a namespace. For example, the following causes a build error.
namespace Example.Program
{
      using Example.Sample;
 
      class Program
      {
            static void Main(string[] args)
            {
                  Something s = new Something();
            }
      }
}
 
namespace Example.Sample
{
      public class Something { }
}
 
namespace Example
{
      public class Example
      {
      }
}
Error   1: The type name ‘Sample’ does not exist in the type ‘Example.Example’
Error   2: The type or namespace name ‘Something’ could not be found (are you missing a using directive or an assembly reference?)
Error   3: The type or namespace name ‘Something’ could not be found (are you missing a using directive or an assembly reference?)
 
I’m not sure why this difference is here or what the benefit is but for better or worse this is how it works. You could also argue that it’s not a good idea to have a class name conflict with a namespace name but, unfortunately, this isn’t always under your own control.
So the thing is that putting your using statements outside of your namespace seems to fix these build errors, so I don’t know why it would ever be preferable to put these using statements inside of your namespace (as recommended by StyleCop by default, for example).

Poor Mans Delegate IOC container

I have been doing some unit testing and mocking in a new application I am working on and I have come to appreciate the need for an IOC Container. I know there are several well established IOC Container frameworks out there (http://csharp-source.net/open-source/containers) but it seemed like such a simple idea I decided to make my own. I created a very very simple Container using lambda expressions and Func<> delegates.

public static class Container
{
    private static Dictionary<Type, Delegate> _registrations
        = newDictionary<Type, Delegate>();

    public static void Initialize()
    {
        _registrations.Clear();
    }

    public static void Register<TResult>(Func<TResult> create)
    {
        Register(typeof(TResult), create);
    }

    public static void Register<T, TResult>(Func<T, TResult> create)
    {
        Register(typeof(TResult), create);
    }

    public static void Register<T1, T2, TResult>(Func<T1, T2, TResult> create)
    {
        Register(typeof(TResult), create);
    }

    public static void Register(Type type, Delegate create)
    {
        if (_registrations.ContainsKey(type))
            throw new InvalidOperationException("Same key registered twice");

        _registrations.Add(type, create);
    }

    public static T Create<T>(paramsobject[] args)
    {
        Type key = typeof(T);
        if (!_registrations.ContainsKey(key))
            throw new InvalidOperationException("Key not registered in container");

        return (T)_registrations[typeof(T)].DynamicInvoke(args);
    }
}

So there are really three methods, Initialize, Create and Register. The last register is the most important the rest are simple helpers.

So imagine in your application you had the following dependency situation:

public class Foo
{
    IBar _bar;
    public Foo()
    {
        _bar = new Bar(this);
    }
}
 
public class Bar
{
    public Bar(IFoo foo) { }
}
Here we are directly instantiating some specific type inside of another type, thus creating a dependency. One way to break this dependency is to introduce Interfaces and an IOC container to use as the factory with which you create your types. For example:
public interface IFoo { }

public interface IBar { }

public class Foo : IFoo
{
    IBar _bar;
    public Foo()
    {
        _bar = Container.Create<IBar>(this);
    }
}

public class Bar : IBar
{
    public Bar(IFoo foo) { }
}

Instead of directly instantiating Bar we are now using the container to create an IBar for us. So now all we have to do is register a type with the container at either application initialization or in the test Setup method. For example:

Container.Register<IFoo>(() => { returnnewFoo(); });
Container.Register<IFoo, IBar>((IFoo f) => { returnnewBar(f); });
IFoo foo = Container.Create<IFoo>();

Calling Create on the Container for IFoo will result in calling the IFoo registered lambda expression which will result in another call to the IBar registration. This breaks the dependencies so we can effectively test the Foo class now. Here is an example of how you might mock the Bar class using Rhino mocks:

IBar mockBar = MockRepository.GenerateMock<IBar>();
Container.Register<IFoo, IBar>((IFoo f) => { return mockBar; });
IFoo foo = newFoo(); 

We are generating a mock IBar then registering it in the container. Now when we call the constructor on Foo it will use the container to create an IBar which will pass it the mock object we created. From here we can setup expectations and verify all values on foo as normal without having to worry about side effects.

This is so powerful to me that it’s almost worth saying that I believe a unit test should only test a single instance in your application per test. In this application I am working on this is my goal and I am starting to see the benefits of such an approach.
If you do not break your dependencies then your unit tests tend to tell you something valuable when they pass but tend to not tell you anything valuable when they fail. If you find yourself running a unit test suite and feeling that it is ok if a few tests fail then it may be time to start breaking up your dependencies.

LINQ methods under the hood

As an intellectual exercise I decided to write up 3 different ways to perform the same LINQ tasks. Actually I saw a comment on one of Don Box’s blog posts where someone asked why the Find and Exists methods weren’t static and I suddenly realized that they were, just with different names!

Since LINQ is simply an internal DSL that wraps calls to extension methods I realized these methods must exist for us to call them explicitly as well. Here is how you can perform a Find or an Exists using LINQ (or not).
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
 
// Find an assembly that starts with System.
Func<Assembly, bool> startsWithSystem = a => a.FullName.StartsWith(“System”);
 
//List<T>.Exists equivalents for any enumerable
bool extensionAny = assemblies.Any(startsWithSystem);
bool explictAny = Enumerable.Any(assemblies, startsWithSystem);
bool linqAny = (from a in assemblies where startsWithSystem(a) select a).Any();
Debug.Assert(extensionAny == explictAny == linqAny == true);
 
// List<T>.Find equivalents for any enumerable
int extensionWhere = assemblies.Where(startsWithSystem).Count();
int explicitWhere = Enumerable.Where(assemblies, startsWithSystem).Count();
int linqWhere = (from a in assemblies where startsWithSystem(a) select a).Count();
Debug.Assert(extensionWhere == explicitWhere && extensionWhere == linqWhere);

CSharp is C plus plus plus plus

I learned something interesting today while reading one of the RSS feed items in the Visual Studio start page. The article in question is an interview with Anders Hejlsberg who says that the idea for the # in C# came from taking C++++ and stacking the pluses (amongst other reasons). I always wondered why they ended up going with the # symbol…

The A-Z of Programming Languages: C#

CSLA Light PropertyStatus control in Action

I have been working on CSLA Light for a while now and one of the coolest things I’ve gotten to work on is the “PropertyStatus” control. It turns out that creating controls for Silverlight is a huge pain in the neck but I think this one turned out pretty well actually.

So what the property status control does is that once bound to a CSLA business object it will hook into PropertyChanged events and display the properties IsBusy status and various broken rules. It will also disable / make read-only another control based on the authorization rules specified in the object. All in all it’s pretty useful.

I put together a quick little video demonstrating the effects. The second half of the video I have logged in under “Guest” credentials to show how it works with authorization.