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.

XAML 2009 Feature List

Yesterday I watched the PDC video about XAML called Microsoft .NET Framework: Declarative Programming Using XAML. It was pretty interesting and it had a list of some of the new features we can expect to see for XAML in the next version of the .NET framework. Here is a brief laundry list along with my (interpreted) explanation.

Better Name References
It used to be you had to create references to other elements using the ElementName property of Binding extensions. Well it seems now that they have created a simpler x:Reference markup extension which will be the default for properties such as the Target property of a Label. Meaning you only have to write the name of the element to get a binding to another control in some places.
XAML 2006
<Label Target=”{Binding ElementName=firstName}>First Name</Label>
<TextBox Name=“firstName” />
XAML 2009
<Label Target=“firstName”>First Name</Label>
<TextBox Name=“firstName” />
Expressions:
Interestingly enough they also touched on a new feature called expressions. The full power and syntax of expressions wasn’t fully explained but at first look they could be extremely useful. Below is an example of an expression that is the string literal “Hello” plus the value of the default property of the firstName element (being that it is a textbox I’m assuming the default property is the Text property).
<TextBox Text=‘[“Hello ” + firstName]’ />
Built-in Types
Currently you have to hook up some gnarly xmlns reference to get access to basic types. They are including access to the most common basic types by default into the ‘x’ namespace for us.
XAML 2006
<s:String xmlns:s=“clr-namespace:System;assembly=mscorlib”>Foo</s:String>
XAML 2009
<x:String>Foo</x:String>
Generics support everywhere
This is very intriguing, clearly this should be useful. I was fully expecting them to come up with something very clever and much more terse then what I see here (new syntax) but what they came up with was actually probably very easy to implement. They simply created a new attached property that stores the type arguments. I’m assuming if you have multiple type arguments you would separate them with a comma.
XAML 2006
classPersonCollection : ObservableCollection<Person>
{ }
 
<c:PersonCollection>
       <c:Person Name=“Dan” />
<c:PersonCollection>
XAML 2009
<ObservableCollection x:TypeArguments=“c:Person”>
       <c:Person Name=“Dan” />
</ObservableCollection>
My proposed generics syntax
If I was going to implement a generics syntax I probably would have favored something more like this
<ObservableCollection[c:Person]>
       <c:Person Name=“Dan” />
</ObservableCollection>
Support arbitrary dictionary key types
I haven’t experienced this as a pain point in doing WPF XAML but it seems that this feature is targeting WF more than anything. Note the example also combines examples of expressions, generics and simple type references. I bet the WF people will be happy about this one.
XAML 2006
<x:Key></x:Key>
XAML 2009
<Switch x:TypeArguments=“x:Int64” Expression=“[rating]”>
       <Sequence x:Key=“10”></Sequence>
       <Sequence>
              <x:Key>9</x:Key>
       </Sequence>
</Switch>
Beyond Method Names
Honestly I couldn’t quite fathom what he was talking about here. This must also be more targeted for WF people because I can’t really see how this would impact WPF at all.
XAML 2006
<Button Click=“button_Click” />
+ markup compilation
XAML 2009
<Button Click=“button_Click” />
+ markup compilation
Also:
<Button Click=”{Delegate Foo} />
 
Better declarative Type Authoring
Once again, this appears to be an improvement mostly for the WF crowd. After talking to Rocky Lhotka briefly he explained that it would be extremely useful to be able to declare your properties as In or Out arguments so that consumers your activities would know what to expect.
XAML 2006
<Window x:Class=“WpfApplication1.Window1” … />
XAML 2009
<Activity x:Class=“ActivityLibrary1.Prompt”>
       <x:SchemaType.Members>
              <x:SchemaProperty Name=“Text” Type=“InArgument(x:String)” />
              <x:SchemaProperty Name=“Result” Type=“OutArgument(x:String)” />
       </x:SchemaType.Members>
</Activity>
Non-default constructors
This sounds useful in general, coupled with simple type references it seems pretty easy to get any type of object you want.
XAML 2006
<x:DateTime>00:00:00.0000100</x:DateTime>
XAML 2009
<DateTime>
       <x:Arguments>
              <x:Int64>100</x:Int64>
       </x:Arguments>
</DateTime>
Use static factory methods
I’m really happy to see this one, the lack of support for factory methods was pretty disappointing to me in the past. The workaround was to use an ObjectDataProvider and specify the MethodName property, which would, unfortunately, force you to have a public default constructor for your object before it could get to your factory. This really messes with your object model, now we should be able to go directly to a factory method. There are still benefits to using the ObjectDataProvider though, I hope there is a way to get the ODP to access the factory methods without requiring a default constructor too.
XAML 2006
Guid guid = Guid.NewGuid();
XAML 2009
<x:Guid x:FactoryMethod=“Guid.NewGuid” />
Composes with x:Arguments