Sasha
Sasha

Reputation: 1411

Singleton's stateless instance method thread safety (C#)

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);}
}

Upvotes: 2

Views: 813

Answers (3)

Guffa
Guffa

Reputation: 700152

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);}

}

Upvotes: 1

driis
driis

Reputation: 164281

Yes, the implementation does nothing that depend on state.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1499770

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.

Upvotes: 2

Related Questions