views:

193

answers:

3

Is it thread safe to make Converter a singleton?

public interface IConverter<TFoo, TBar>
    where TFoo : class, new()
    where TBar : class, new()
{
    TFoo ToFoo(TBar q);
    TBar ToBar(TFoo q);
}

public class Converter : IConverter<Foo, Bar>
{
    public Foo ToFoo(Bar b) {return new Foo(b);}
    public Bar ToBar(Foo f) {return new Bar(f);}
}
+2  A: 

Yes, that's absolutely fine. There's no state, thus no thread safety issues - and there's no reason to have multiple instances. It's a fairly natural singleton.

Of course it's nice to use the interface where you can, for flexibility and testability - but when you know you want to use that specific implementation, a singleton instance is fine.

Jon Skeet
Thanks for the quick answer. Indeed surprised by the speed :-)I plan to use it through the interface. Instantiation will actually be performed by StructureMap lib.
alexander
+2  A: 

Yes, the implementation does nothing that depend on state.

driis
+1  A: 

Yes, as the class has no data members, you can make it a singleton.

As the class is so small, you can just create a static instance of it:

public class Converter : IConverter<Foo, Bar> {

  private static _instance = new Converter();

  public static Instance { get { return _instance; } }

  public Foo ToFoo(Bar b) {return new Foo(b);}
  public Bar ToBar(Foo f) {return new Bar(f);}

}
Guffa
Thanks. Regarding proposed singleton implementation:Is it OK to omit declaration of "Explicit static constructor to tell C# compiler not to mark type as beforefieldinit"? (http://www.yoda.arachsys.com/csharp/singleton.html)
alexander
@alexander: Yes, as it doesn't matter exactly when the instance is created, there is no practical difference.
Guffa